Childrens and Layers

Hi guys,
i had problem while doing loop for all element children’s and change their layer but i had a little problem
So here’s the code

            gameObject.layer = 9;
            foreach (GameObject child in gameObject)
            {
                child.layer = 9;
            }

and the problem
error CS1579: foreach statement cannot operate on variables of type UnityEngine.GameObject' because it does not contain a definition for GetEnumerator’ or is not accessible

You can’t iterate over a GameObject’s children like that. You need to use its Transform.childCount and Transform.GetChild().

Thanks, i’ll try that

You want to loop over the transform, not the gameObject.

foreach (Transform child in transform)

Does this work? I didn’t realize Transform implemented the IEnumerable interface.

Yep - it’s the first script example in the docs.

1 Like

Bizarre… They couldn’t do something reasonable like Transform.Children…

Anyways, just so I’m contributing:

foreach (Transform child in transform)
  child.gameObject.layer = 9;

i fixed it by doing this :

            Transform[] childrens = gameObject.GetComponentsInChildren<Transform>();
            foreach(Transform child in childrens)
            {
                child.gameObject.layer = 9;
            }

Anyways ty