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;
    }

這樣,是不是簡單了很多,比用迭代一層一層去超找簡單,而且也好理解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM