递归查找子物体/获取子物体上组件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Globe : MonoBehaviour {

    public static Transform FindChild(Transform parent, string name)
    {
        Transform item = null;
        //寻找自身一级目录下的子物体有没有该名字的子物体
      item=  parent.FindChild(name);
       //如果有,返回他
      if (item != null) return item;
      Transform go = null;
        //如果没有,就吧该父物体所有一级子物体下所有的二级子物体找一遍(以此类推)

      for (int i = 0; i < parent.childCount; i++)
      {
       go=   FindChild(parent.GetChild(i), name);
       if (go != null)
           return go;
      }
      return null;
    }


    public static T FindChild<T>(Transform parent,string name) where T:Component
    {
       Transform item=null;
       item= FindChild(parent, name);
       if (item != null)
           return item.GetComponent<T>();
       return null;
    }
}

猜你喜欢

转载自blog.csdn.net/fuliyefly/article/details/78289021