using UnityEngine;
public class GetChilds
{
//使用 静态关键字进行修饰便于外部进行修饰
public static GameObject GetChild(Transform trans, string childName)
{
//得到当前脚本挂在的对象
Transform child = trans.Find(childName);
//找到的时候
if (child != null)
{
//返回一个游戏对象
return child.gameObject;
}
//得到所有的子物体个数
int count = trans.childCount;
//定义一个新的对象
GameObject go = null;
//遍历所有的对象
for (int i = 0; i < count; ++i)
{
//拿到当前对象下面所有的子对象
child = trans.GetChild(i);
//获取对象并赋值
go = GetChild(child, childName);
//不为空的时候返回出去
if (go != null)
{
return go;
}
}
return null;
}
//使用 泛型 进行修饰,可以是任意类型,约束为必须是 Component类型,也就是我们所有组件的基类
public static T GetChild<T>(Transform trans, string childName) where T : Component
{
//赋值给对象
GameObject go = GetChild(trans, childName);
if (go == null)
{
return null;
}
return go.GetComponent<T>();
}
}