Unity 遍历子物体与孙物体

遍历子物体方式

找到子物体,常用于将子物体赋值到List中,缺点明显,只能遍历当前物体的所有子物体,但不包含孙物体

    foreach (Transform child in this.transform)
    {
        Debug.Log("所有该脚本的物体下的子物体名称:" + child.name);
    }
遍历子物体方式扩展

找到子物体便于批量操作,主要用于删除,同样不包含孙物体

	List<Transform> lst = new List<Transform>();
    foreach (Transform child in this.transform)
    {
    	lst.Add(child);
    	Debug.Log("所有该脚本的物体下的子物体名称:" + child.gameObject.name);
    }
    //可以批量操作
    for (int i = 0; i < lst.Count; i++)
    {
    	GameObject.Destroy(lst[i].gameObject);
    }
    lst=null;

遍历子物体与孙物体方式

使用以下两种方式时注意看清Component

  1. 根据组件获取 GetComponentsInChildren<Component>(true)
	//(true)表示可以将隐藏的物体也获取到
    Transform[] allTrans = this.gameObject.GetComponentsInChildren<Transform>(true);
    for (int i = 0; i < allTrans.Length; i++)
    {
        Debug.Log("所有该脚本的物体下的子物体和孙物体名称:" + allTrans[i].gameObject.name);
    }
  1. 递归查找,直接调用 FindGameObject(Transform t) 方法即可
   public void FindGameObject(Transform t)
   {
          Transform[] trans = FindChild(t);
          if (trans == null)
              return;
          for (int i = 0; i < trans.Length; i++)
          {
              FindGame(trans[i]);
          }
    }
    private int count;
    public Transform[] FindChild(Transform t)
    {
          Transform[] trans = new Transform[t.childCount];
          if (t.childCount > 0)
          {
              for (int i = 0; i < t.childCount; i++)
              {
                  count++;
                  trans[i] = t.GetChild(i);
              }
              for (int i = 0; i < trans.Length; i++)
              {
              	Debug.Log("所有该脚本的物体下的子物体和孙物体名称:" + trans[i].gameObject.name);
              }
              return trans;
          }
          else
              return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值