Unity动态添加tag

1、 做的项目中 需要动态给物体创建一个tag,并添加给物体,但是出现了bug,想要给物体添加tag的话,必须要在编辑器面板中先声明,才可以用代码添加。
2、下面实现了 用代码动态添加tag,不需要先在编辑器中添加,首先要引入命名空间
using UnityEditor; 所以此方法只适合在编辑器下使用。
3、简单粗暴,直接上代码

#region 动态添加tag
        void AddTag(string tag, GameObject obj)
        {
            if (!isHasTag(tag))
            {
                SerializedObject tagManager = new SerializedObject(obj);//序列化物体
                SerializedProperty it = tagManager.GetIterator();//序列化属性
                while (it.NextVisible(true))//下一属性的可见性
                {
                    if (it.name == "m_TagString")
                    {
                        Debug.Log(it.stringValue);
                        it.stringValue = tag;
                        tagManager.ApplyModifiedProperties();
                    }
                }
            }
        }
        bool isHasTag(string tag)
        {
            for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.tags.Length; i++)
            {
                if (UnityEditorInternal.InternalEditorUtility.tags[i].Equals(tag))
                    return true;
            }
            return false;
        }
        #endregion

猜你喜欢

转载自blog.csdn.net/weixin_43109909/article/details/83150696