遍历子物体方式
找到子物体,常用于将子物体赋值到List中,缺点明显,只能遍历当前物体的所有子物体,但不包含孙物体
foreach (Transform child in this.transform)
{
Debug.Log("所有该脚本的物体下的子物体名称:" + child.name);
}
遍历子物体方式扩展
找到子物体便于批量操作,主要用于删除,同样不包含孙物体
List<Transform> lst = new List<Transform>();
foreach (Transform child in this.transform)
{
lst.Add(child);
Debug.Log("所有该脚本的物体下的子物体名称:" + child.gameObject.name);
}
//可以批量操作
for (int i = 0; i < lst.Count; i++)
{
GameObject.Destroy(lst[i].gameObject);
}
lst=null;
遍历子物体与孙物体方式
使用以下两种方式时注意看清Component
- 根据组件获取 GetComponentsInChildren<Component>(true)
//(true)表示可以将隐藏的物体也获取到
Transform[] allTrans = this.gameObject.GetComponentsInChildren<Transform>(true);
for (int i = 0; i < allTrans.Length; i++)
{
Debug.Log("所有该脚本的物体下的子物体和孙物体名称:" + allTrans[i].gameObject.name);
}
- 递归查找,直接调用 FindGameObject(Transform t) 方法即可
public void FindGameObject(Transform t)
{
Transform[] trans = FindChild(t);
if (trans == null)
return;
for (int i = 0; i < trans.Length; i++)
{
FindGame(trans[i]);
}
}
private int count;
public Transform[] FindChild(Transform t)
{
Transform[] trans = new Transform[t.childCount];
if (t.childCount > 0)
{
for (int i = 0; i < t.childCount; i++)
{
count++;
trans[i] = t.GetChild(i);
}
for (int i = 0; i < trans.Length; i++)
{
Debug.Log("所有该脚本的物体下的子物体和孙物体名称:" + trans[i].gameObject.name);
}
return trans;
}
else
return null;
}