Help with Layer change in all Children

Hi, you know how when you change a layer in the Inspector and it asks you weather you want to make the same change for all of this children Layers also. I would Like to how to implement this when I change the layer in code.

Thanks in advance.

Here is my current Code, but atm it does not change the layer of the children.

HealthBarRotation tempSave = myUnit.gameObject.GetComponentInChildren<HealthBarRotation>();
                tempSave.gameObject.layer = 19;

                Debug.Log(tempSave.gameObject.layer);

Something like this should work:

         foreach (Transform child in transform)
         {
                 child.gameObject.layer = 19;
         }
6 Likes

Love you, thanks bro

1 Like

This works for 1 level of children but if there are nested children you need to accomplish this via recursion. This example work set all nested children’s layer to the correct value:

private void SetGameLayerRecursive(GameObject _go, int _layer)
        {
            _go.layer = _layer;
            foreach (Transform child in _go.transform)
            {
                child.gameObject.layer = _layer;

                Transform _HasChildren = child.GetComponentInChildren<Transform>();
                if (_HasChildren != null)
                    SetGameLayerRecursive(child.gameObject, _layer);
              
            }
        }
8 Likes

“To understand recursion, you must first understand recursion.”

I actually favor the “get all Transforms in children” approach.

    void SetLayerAllChildren(Transform root, int layer)
    {
        var children = root.GetComponentsInChildren<Transform>(includeInactive: true);
        foreach (var child in children)
        {
//            Debug.Log(child.name);
            child.gameObject.layer = layer;
        }
    }

Bonus: works with RectTransforms transparently.

24 Likes

Thank you, this was very useful

1 Like

Found helpful in early 2023. Still wondering why Unity doesn’t just add a flag to gameobject.layer to include children.

gameobject.layerAllChildren perhaps

4 Likes

foreach (GameObject gameObject in GetComponentsInChildren())
{
gameObject.layer = 1;
}

This doesn’t make much sense and would not compile at all since GameObject is not a component and therefore can not be returned by GetComponentsInChildren. Also even when done properly by using a component that each child has (Transform is the best choice here) your solution would be the same what Kurt suggested 2 years ago.

I did it similarly, just a bit simpler:

        private void SetGameLayerRecursive(GameObject gameObject, int layer)
        {
            gameObject.layer = layer;
            foreach (Transform child in gameObject.transform)
            {
                SetGameLayerRecursive(child.gameObject, layer);
            }
        }
2 Likes