Unity's method of obtaining the child objects of an object

To get the child objects of an object in Unity, you can use the following methods.

1. Get only the child objects of the first-level node:

    public Transform tran;
    // Start is called before the first frame update
    void Start()
    {
        foreach (Transform child in tran)
        {
            Debug.Log(child.name);
        }
    }

Using this method will only obtain the child objects of the first-level node in the object.

2. To get the child objects of all nodes of the object, use the GetComponentsInChildren method:

    public Transform tran;
    // Start is called before the first frame update
    void Start()
    {
        foreach (Transform child in tran.GetComponentsInChildren<Transform>())
        {
           Debug.Log(child.name);
        }
    }

Using the above method you can get the child objects of all nodes in the object, but it will include the object itself.

Using the GetComponentsInChildren method, you can also obtain child objects of a specified type. This is particularly useful, such as:

Renderer[] renderers = GetComponentsInChildren<Renderer>();

3. There is also a more commonly used method, which is to use the GetChild() method of the Transform component.

This method obtains the sub-object by its index. The index starts from 0 and is numbered according to the order of the sub-object in the hierarchy.

    void Start()
    {
        // 获取当前物体的 Transform 组件
        Transform parentTransform = transform;

        // 遍历所有子物体
        for (int i = 0; i < parentTransform.childCount; i++)
        {
            // 获取子物体的 Transform 组件
            Transform childTransform = parentTransform.GetChild(i);

            // 在这里可以对子物体进行操作,例如打印子物体的名称
            Debug.Log("子物体名称:" + childTransform.name);
        }
    }

Guess you like

Origin blog.csdn.net/mr_five55/article/details/134700822