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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值