方法一:通过transform
int index_FirstChild = 0; // 获取index对应的子物体
Transform pchild = player.transform.GetChild(index_FirstChild);
print(pchild.gameObject.name);
在上述方法上进行递归,就可以获取所有的子物体,以及子物体的子物体...
打印一个物体player的所有子物体:
// 递归函数定义
public void SearchAllChildren(Transform father) {
print(father.name);
for (int i = 0; i < father.transform.childCount; i++)
{
SearchAllChildren(father.transform.GetChild(i));
}
return;
}
// 从对象player开始递归
Transform pchild = player.transform.GetChild(index_FirstChild);
SearchAllChildren(pchild);
方法二:通过获取特定类型的Component,反推其依附的对象。我们只要找到了一个名为xxx的脚本,就可以获得这个对象的全部信息。但是要注意,这个函数也会找寻到父对象自己,需要找那些绑定了独特脚本的对象时,才考虑使用:
// 其中ScrollBehaviour.cs是独特存在于某个子对象中的独特脚本名称
ScrollBehaviour tchild = player.GetComponentInChildren<ScrollBehaviour>();
print(tchild.name);