查看: 1337|回复: 0
打印 上一主题 下一主题

[其他] Unity3D动态添加tag的代码

[复制链接]

9903

主题

126

听众

7万

积分

首席设计师

Rank: 8Rank: 8

纳金币
53520
精华
316

最佳新人 热心会员 灌水之王 活跃会员 突出贡献 荣誉管理 论坛元老

跳转到指定楼层
楼主
发表于 2017-11-29 19:11:03 |只看该作者 |倒序浏览
  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. }
复制代码
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

手机版|纳金网 ( 闽ICP备2021016425号-2/3

GMT+8, 2025-6-28 06:49 , Processed in 0.085930 second(s), 28 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部