从父游戏对象中找到所有子游戏对象,并将其分配给var游戏对象?

时间:2019-06-27 13:40:39

标签: c# unity3d

我如何找到父级的所有子级gameObject(包括以下子项:parent-child-children ..)并将其分配给gameObject?

下面的脚本查找其当前父级的所有子级gameObject,但找不到找到的子级的子级子gameObject。

public GameObject parent;
private GameObject AssignedChild;

 foreach (Transform eachChild in parent.transform)
        {
            if (eachChild.gameObject.tag == "TagOfTheObject")
            {
               //assign the tagged GameObject to "AssignedChild" GameObject
               AssignedChild = eachChild.gameObject;
            }

        }

1 个答案:

答案 0 :(得分:0)

我只需要添加一行即可找到所有子代的gameObjects

public GameObject parent;
private GameObject AssignedChild;

 foreach (Transform eachChild in parent.GetComponentsInChildren<Transform>())
        {
            if (eachChild.gameObject.tag == "TagOfTheObject")
            {
               //assign the tagged GameObject to "AssignedChild" GameObject
               AssignedChild = eachChild.gameObject;
            }

        }