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

版权声明:本文为博主原创文章,未经博主允许不得用于任何商业用途,转载请注明出处。 https://blog.csdn.net/beihuanlihe130/article/details/76216534

在Unity的编辑器中,当我们有较多的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();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/beihuanlihe130/article/details/76216534