Unity在编辑器中通过代码更改Tag

发表于2018-09-29
评论0 4k浏览
这篇文章给大家分享在Unity的编辑器中,通过代码来更改Tag,那为何要如此操作,主要是因为在有有较多的Tag需要手动输入时,我们可以通过代码来简化此过程,同时也可以通过代码将我们的工程导入其他项目时来检查需要的Tag是否存在。同时,在AssetBundle导出的过程中,虽然模型中的Tag会被保留,但是其保存的仅仅是Tag列表中的一个顺序,而非真正的根据名称保存的。这就需要当我们在不同的项目中进行Bundle的导入导出时重点检查的部分,否则容易出现意想不到的结果。

代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class CheckTags : MonoBehaviour
{
    private static string[] tags = new string[] {
        "***"
        "***"
        "***"
        "***"
        "***"
        "***"
        "***"
        "***"};
    [MenuItem("TagController/CheckTags")]
    public static void CheckTag()
    {
        // Open tag manager
        SerializedObject tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
        // Tags Property
        SerializedProperty tagsProp = tagManager.FindProperty("tags");
        //Debug.Log("TagsPorp Size:" + tagsProp.arraySize);
        tagsProp.ClearArray();
        tagManager.ApplyModifiedProperties();
        //Debug.Log("TagsPorp Size:" + tagsProp.arraySize);
        for (int i = 0; i < tags.Length; i++)
        {
            // Insert new array element
            tagsProp.InsertArrayElementAtIndex(i);
            SerializedProperty sp = tagsProp.GetArrayElementAtIndex(i);
            // Set array element to tagName
            sp.stringValue = tags[i];
            tagManager.ApplyModifiedProperties();
        }
    }
}

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引