纳金网

标题: Unity3D动态添加tag的代码 [打印本页]

作者: 烟雨    时间: 2017-11-29 19:11
标题: Unity3D动态添加tag的代码
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEditor;

  4. public class DemoText : MonoBehaviour {

  5.         // Use this for initialization
  6.         void Start () {
  7.      bool b =   isHasTag("Player");   //随意挂载进行测试
  8.         Debug.Log(b);
  9.       GameObject cube =  GameObject.CreatePrimitive(PrimitiveType.Cube);
  10.         AddTag("Zombie",cube);  
  11.     }
  12.        
  13.         // Update is called once per frame
  14.         void Update () {
  15.        
  16.         }


  17.     //动态添加tag
  18.     private static void AddTag(string newtag, GameObject obj)
  19.     {
  20.         if (!isHasTag(newtag))
  21.         {
  22.             SerializedObject tagManager = new SerializedObject(obj);
  23.             SerializedProperty pro = tagManager.GetIterator();
  24.             while (pro.NextVisible(true))
  25.             {
  26.                 if (pro.name == "m_TagString")
  27.                 {
  28.                     pro.stringValue = newtag;
  29.                     tagManager.ApplyModifiedProperties();
  30.                 }
  31.             }
  32.         }
  33.         else
  34.         {
  35.             obj.tag = newtag;
  36.         }
  37.     }

  38.     static bool isHasTag(string newtag)
  39.     {
  40.         for (int i = 0; i < UnityEditorInternal.InternalEditorUtility.tags.Length; i++)
  41.         {
  42.             if (UnityEditorInternal.InternalEditorUtility.tags[i].Equals(newtag))
  43.             {
  44.                 return true;
  45.             }
  46.         }
  47.         return false;

  48.     }
  49. }
复制代码





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5