02、在层级未知情况下通过递归查找子物体

1、在在层级未知情况下通过递归查找子物体 ,这个主要是用于UI的的层级查找中

2、代码:

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class EnemyManager : MonoBehaviour
 6 {
 7 
 8     private  GameObject t;
 9     private  string name_1 = "Cube_05";
10     private void Start()
11     {
12         t = FindChildByName(this.gameObject,name_1);
13          print(t.name);
14     }
15 
16     /// <summary>
17     /// 在不知道层级的情况下,查找指定名字的子物体
18     /// </summary>
19     /// <param name=""></param>
20     /// <returns></returns>
21     public  GameObject FindChildByName(GameObject parent, string childName)
22     {
23         if (parent.name == childName)        //如果要查找的就是这个物体本身
24         {
25             return parent;
26         }
27         if (parent.transform.childCount < 1)   //如果要查找的物体孩子数量为0,则跳出方法,进行下一个判定
28         {
29             return null;     
30         }        
31         GameObject obj = null;
32         for (int i = 0; i < parent.transform.childCount; i++)
33         {
34             GameObject go = parent.transform.GetChild(i).gameObject;            
35             obj = FindChildByName(go, childName);   //进行递归的调用,递归查找
36             if (obj != null)
37             {
38                 break;
39             }
40         }
41         return obj;
42     }
43 }

 3、总结:可以将这个方法提取出来一个工具类来进行使用,因为后续实用性挺强的。

原文地址:https://www.cnblogs.com/zhh19981104/p/9572769.html