Unity 中 GetComponentsInChildren 的应用

在实际项目中,我们经常要去查找一个节点下的某个子节点,但是子节点太多,或者每次我们都要去自己写GameObject.FindChald("xxx")实在是太过繁琐,那么这是后就可以用GetComponentsInChildren了

,他返回的是要查找的这个节点下的所有子节点和要超找的对象本身的Transform数组,然后我们再用for循环遍历,便可以找到我们想要的了,废话不多说,我们看代码

    public Transform FindChild(Transform parent, string childname)
    {
        Transform child = parent.Find(childname);
        if (child != null)
        {
            return child;
        }

        Transform[] tranArray = parent.GetComponentsInChildren<Transform>(true);
        Debug.Log(tranArray.Length);
        for (int i = 0; i < tranArray.Length; ++i)
        {
            Transform tran = tranArray[i];
            Debug.Log(tran.name);
            if (tran.name == childname)
            {

                return tran;
            }
        }
        return null;
    }

这样,是不是简单了很多,比用迭代一层一层去超找简单,而且也好理解

posted @ 2017-10-18 13:17  飞天艾特小猪  阅读(7591)  评论(0编辑  收藏  举报