How to Get All children in a GameObject?

Here is GameObject named “xxx”,and I don’t know the names of its children.How can i set its children invisible?I failed like this:

Renderer[] ChildrenRenderer = ObjParent.GetComponentsInChildren(typeof(Renderer)) as Renderer[];
foreach(Renderer abc in ChildrenRenderer )
  abc.enabled=false;

why?

Thats because safecasting(‘as’) doesnt handle arrays to well in my experience. GameObject.GetComponents() returns a Components[ ]. Just rewrite your this line Renderer[] ChildrenRenderer = ObjParent.GetComponentsInChildren(typeof(Renderer)) as Renderer[];

to

Renderer[] ChildrenRenderer = ObjParent.GetComponentsInChildren(typeof(Renderer));

That should do it.

1 Like

i delete “as Renderer[ ]”,it says:

Assets/Script/main.cs(66,24): error CS0266: Cannot implicitly convert type UnityEngine.Component[ ]' to UnityEngine.Renderer[ ]'. An explicit conversion exists (are you missing a cast?)

and when i add “as Renderer[ ]”,it says:

NullReferenceException: Object reference not set to an instance of an object

still How to Get All children in a GameObject?forget the Renderer…

The Transform class is IEnumerable, so simply loop over it to get all child transforms:

// Moves all transform children 10 units upwards!
for (var child : Transform in transform) {
    child.position += Vector3.up * 10.0;
}

I think Slem made a typo. Because GetComponents() returns Component[ ], ChildrenRenderer has to be of type Component[ ]. The foreach loop will still work as written, because it will cast each Renderer properly as it iterates.

thx!

GetComponentsInChildren<Collider>();

That’s the correct way

2 Likes

My favourite C# way…

foreach (Transform child in transform)
            child.gameObject.renderer.enabled = false;
3 Likes

The enumerator method is shown in the Transform scripting reference: Unity - Scripting API: Transform

But you can also use the Transform childCount variable and GetChild function.

I like how there is no GetChildren method. Its like… What?

1 Like

How can one do this in the editor scripting side, where there is no transform property? I have an fbx model that I want to do something to all of its children, but there are too many to do it all manually.

Gonna bump this.

Anyone knows how to find Children gO attached to specific named gO?

This:

GameObject g4 = GameObject.Find("MyMainGO");
            if (g4 != null)
            {
                foreach (object obj in g4.transform)
                {
                    Transform child = (Transform)obj;
                    Debug.Log("Children is: " + child.name);
                }
            }
        }

Does not work properly.

1 Like

Why? This thread is so out of date as to be essentially useless. A lot has changed since 2009. Start a new thread.

Also it’s not related to the original question. Don’t bump this!