获取所有 child 游戏 objects 的最佳做法?

Best practice for getting all child game objects?

您好:-) 我是 Unity3D 的新开发者。 我有一个问题,获取所有 children GameObject 的最佳做法是什么。

我想要在某些情况下激活或 de-active 3 个按钮(相机、SNS、保存按钮)。

这是我的代码。但我认为这并不好。 我想更换它。有很多 foreach 语句。 当添加parent游戏object时,也会添加foreach循环。


var uiRoot = GameObject.Find("UIRoot");
    if (uiRoot != null)
    {

        foreach (Transform camera in uiRoot.transform)
        {
            camera.gameObject.SetActive(true);

            foreach (Transform anchor in camera.transform)
            {
                anchor.gameObject.SetActive(true);

                foreach (Transform buttons in anchor.transform)
                {
                    if (buttons.gameObject.tag == "PictureTag")
                    {
                        buttons.gameObject.SetActive(!isCameraVisible);
                    }
                    else if (buttons.gameObject.tag == "CameraTag")
                    {
                        buttons.gameObject.SetActive(isCameraVisible);
                    }
                }
            }
        }
    }

你们对此有什么好主意吗? 帮帮我,谢谢。

如果目的是获取子游戏对象中的所有组件,那么您可以使用类似这样的方法:

var uiRoot = GameObject.Find("UIRoot");
if (uiRoot != null)
{
    bool includeInactiveGameobjects = true;
    var buttons = uiRoot.GetComponentsInChildren<UIButton>(includeInactiveGameobjects);
    foreach (UIButton uibutton in buttons)
    {
        // Do stuff to button here:
    }
}

这将创建一个可以迭代的 Button 组件集合,并且可以通过在 foreach 循环内的组件上使用 gameObject 属性 来访问它们的关联游戏对象:

...
foreach (UIButton uibutton in buttons)
{
    // Do stuff to button here:
    GameObject gameObject = uibutton.gameObject;
}

干杯!