Unity中获取一个物体下所有的子物体的方法

Unity中获取一个物体下所有的子物体的方法

方法1(获取全部子物体,无论子物体SetActive是否为true):

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

public class Test : MonoBehaviour
{
    
    
     public List<GameObject> CH = new List<GameObject>();//储存物体的列表
    
    // Start is called before the first frame update
    void Start()
    {
    
    
        FindChild(this.gameObject);//找到节点下的所有子物体

    }
    void FindChild(GameObject child)
    {
    
    




        //利用for循环 获取物体下的全部子物体
        for (int c = 0; c < child.transform.childCount; c++)
        {
    
    
            //如果子物体下还有子物体 就将子物体传入进行回调查找 直到物体没有子物体为止
            if (child.transform.GetChild(c).childCount > 0)
            {
    
    
                FindChild(child.transform.GetChild(c).gameObject);

            }
            CH.Add(child.transform.GetChild(c).gameObject);


        }
    }
}

获取全部子物体后,可通过list列表对物体进行批处理;
如添加或移除其子物体的组件,判断其子物体是否有某个组件等等。
方法二(推荐):

transform.GetComponentsInChildren<Transform>(); //无法获取SetActive为false的子物体
transform.GetComponentsInChildren<Transform>(true); //获取全部子物体,无论SetActive是否为true

该方法为Unity内置的API,会查找物体下对应类型的全部组件;
注意:此方法会查找到本身的Transform

猜你喜欢

转载自blog.csdn.net/LCF_CSharp/article/details/123555319