获取多个游戏对象上某个共同属性的思路

假如,现在有个需求,实现获取游戏对象名字的代码?

思考前我的做法是:

内部属性:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemCtrl : MonoBehaviour
{
    GameObject obj = null;
    public GameObject cachedGameObject
    {
        get
        {
            if (null == obj)
                obj = gameObject;
            return obj;
        }
    }

    public string GetName()
    {
        return cachedGameObject.name;
    }
}

外部管理:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LgsTest : MonoBehaviour
{
    ItemCtrl[] arryItem;

    List<string> nameList = new List<string>();

    void CollectItemName()
    {
        nameList.Clear();
        for (int i = 0, iMax = arryItem.Length; i < iMax; ++i)
        {
            nameList.Add(arryItem[i].GetName());
        }
    }
}

思考后我的做法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemCtrl : MonoBehaviour
{
    GameObject obj = null;
    public GameObject cachedGameObject
    {
        get
        {
            if (null == obj)
                obj = gameObject;
            return obj;
        }
    }

    public string GetName()
    {
        return cachedGameObject.name;
    }


    void OnEnable()
    {
        itemList.Add(this);
    }

    void OnDisable()
    {
        itemList.Remove(this);
    }

    static List<ItemCtrl> itemList = new List<ItemCtrl>();
    public static void CollectItemNames(ref List<string> nameList)
    {
        nameList.Clear();

        for (int i = 0, iMax = itemList.Count; i < iMax; ++i)
            nameList.Add(itemList[i].GetName());
    }
}

  

posted @ 2018-05-31 10:32  小·糊涂仙  阅读(245)  评论(0编辑  收藏  举报