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开始,按照子物体在层次结构中的顺序进行编号。

本文介绍了在Unity中获取物体子物体的不同方式:一级节点的子物体、所有节点的子物体(包括自身)以及使用GetChild方法按索引获取。详细展示了每种方法的代码示例。
最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



