Unity 中要获取物体的子物体,可以使用以下一些方法。
1、只获取一级节点的子物体:
public Transform tran;
// Start is called before the first frame update
void Start()
{
foreach (Transform child in tran)
{
Debug.Log(child.name);
}
}
使用该方法只会获取物体中一级节点的子物体。
2、获取物体的所有节点的子物体,使用GetComponentsInChildren方法:
public Transform tran;
// Start is called before the first frame update
void Start()
{
foreach (Transform child in tran.GetComponentsInChildren<Transform>())
{
Debug.Log(child.name);
}
}
使用上面方法可以获取物体中所有节点的子物体,但它会包括该物体本身。
使用GetComponentsInChildren方法,还可以获取某种指定类型的子物体,这个特别好用,如:
Renderer[] renderers = GetComponentsInChildren<Renderer>();
3、还有一种比较常用的方法,即使用Transform组件的GetChild()方法。
这个方法通过子物体的索引获取子物体,索引从0开始,按照子物体在层次结构中的顺序进行编号。
void Start()
{
// 获取当前物体的 Transform 组件
Transform parentTransform = transform;
// 遍历所有子物体
for (int i = 0; i < parentTransform.childCount; i++)
{
// 获取子物体的 Transform 组件
Transform childTransform = parentTransform.GetChild(i);
// 在这里可以对子物体进行操作,例如打印子物体的名称
Debug.Log("子物体名称:" + childTransform.name);
}
}