【问题标题】:Best practice for getting all child game objects?获取所有子游戏对象的最佳实践?
【发布时间】:2015-09-22 00:21:42
【问题描述】:

你好 :-) 我是 Unity3D 的新开发人员。 我有一个问题,让所有孩子 GameObject 的最佳做法是什么。

我想在某些情况下启用或停用 3 个按钮(相机、SNS、保存按钮)。

这是我的代码。但我认为这不好。 我想更换它。有很多 foreach 语句。 添加父游戏对象时,也会添加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);
                    }
                }
            }
        }
    }

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

【问题讨论】:

    标签: unity3d gameobject


    【解决方案1】:

    如果意图是获取子游戏对象中的所有组件,那么您可以使用以下内容:

    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;
    }
    

    干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多