using UnityEngine;
public class BaseGetConmpont
{
//使用 靜態關鍵字進行修飾便於外部進行修飾
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>();
}
}
Unity遞歸獲取對象
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.