Search code examples
unity-game-enginegameobject

Best practice for getting all child game objects?


Hello :-) I'm new developer in Unity3D. I have a question what is the best practice of getting all children GameObject.

GameObject's hierarchy

I wanna active or de-active 3 buttons (Camera, SNS, Save Buttons) under some conditions.

here is my code to do that. but I think this is not good. I would like to replace it. There are so many foreach statements. When the parent game object will be added, foreach loop will be added also.


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

Do you guys have a good idea for that? Help me, Thanks.


Solution

  • If the intention is to grab all the components within the child gameobjects then you can use something like this:

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

    This creates a collection of Button components that can be iterated through and their associated gameObjects can be accessed by using the gameObject property on the component within the foreach loop:

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

    Cheers!