到目前为止,我已经尝试过这个来获取对象的所有子节点,但它只带来两个子对象。不是孩子的全部孩子。我如何获得所有并循环获取特定的名称对象
Transform[] objChild = gameObject.transform.GetComponentsInChildren<Transform>();
for (var i = 0; i < objChild.Length; i++)
{
objWheel.Add(objChild[i].gameObject.transform.GetChild(i).gameObject);
objWheelAnimation.Add(objChild[i].gameObject.transform.GetChild(i).GetComponent<Animation>());
if (objChild[i].gameObject.name.Contains("Wheel Rotation"))
{
}
}
答案 0 :(得分:5)
您必须使用递归:
using System.Collections.Generic;
private List<GameObject> listOfChildren;
private void GetChildRecursive(GameObject obj){
if (null == obj)
return;
foreach (Transform child in obj.transform){
if (null == child)
continue;
//child.gameobject contains the current child you can do whatever you want like add it to an array
listOfChildren.Add(child.gameObject);
GetChildRecursive(child.gameObject);
}
}
希望它可以帮到你
答案 1 :(得分:1)
如果要获取父GameObject的每个子代,则这里是最小,最简单的代码段。将此附加到父GameObject。
foreach (Transform g in transform.GetComponentsInChildren<Transform>())
{
Debug.Log(g.name);
}