How to get all sub-objects under an object in Unity

How to get all sub-objects under an object in Unity

Method 1 (get all sub-objects, regardless of whether the sub-object SetActive is 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);


        }
    }
}

After obtaining all sub-objects, you can batch process the objects through the list;
such as adding or removing components of its sub-objects, determining whether its sub-objects have a certain component, etc.
Method two (recommended):

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

This method is Unity’s built-in API and will find all components of the corresponding type under the object;
(Note: This method will find its own Transform

Guess you like

Origin blog.csdn.net/LCF_CSharp/article/details/123555319