在在层级未知情况下通过递归查找子物体 ,这个主要是用于UI的的层级查找中
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemyManager : MonoBehaviour { private GameObject t; private string name_1 = “Cube_05”; private void Start() { t = FindChildByName(this.gameObject,name_1); print(t.name); } /// /// 在不知道层级的情况下,查找指定名字的子物体 /// /// /// public GameObject FindChildByName(GameObject parent, string childName) { if (parent.name == childName) //如果要查找的就是这个物体本身 { return parent; } if (parent.transform.childCount < 1) //如果要查找的物体孩子数量为0,则跳出方法,进行下一个判定 { return null; } GameObject obj = null; for (int i = 0; i < parent.transform.childCount; i++) { GameObject go = parent.transform.GetChild(i).gameObject; obj = FindChildByName(go, childName); //进行递归的调用,递归查找 if (obj != null) { break; } } return obj; } }