Unity3D 高效率查找子物体(孩子比较多 需要查找的物体比较多的时候)

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

public class TestRes : MonoBehaviour {

    public GameObject go;

    // Use this for initialization
    void Start () {

        GameObject target = GameObject.Instantiate(go) as GameObject;
        List<Transform> findTest = new List<Transform>();

        string[] findNames = new string[]
            { "Directional light","GameObject (3)","GameObject (4)"};

        FindChild(target.transform, new List<string>(findNames), ref findTest);

        for (int i = 0; i < findTest.Count; i++)
        {
            if (findTest[i].name.Equals(findNames[0])) 
            {
                Light li = findTest[i].GetComponent<Light>();
                if (li != null)
                {
                    li.color = Color.black;
                    Debug.Log(li.color);
                }
            }
            else
            {
                Debug.Log(findTest[i].name);
            }


        }

    }

    void FindChild(Transform go,List<string> findName, ref List<Transform> trf)
    {
        if (trf.Count == findName.Count)
        {
            return;
        }
        if (findName.Contains(go.name))
        {
            trf.Add(go);
        }
        if (go.childCount != 0)
        {
            for (int i = 0; i < go.childCount; i++)
            {
                FindChild(go.GetChild(i), findName, ref trf);
            }
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容