Unity: Run an action on all children of a gameobject

Handy piece of code that will run an action on all children of a gameobject.

using System;
using UnityEngine;

public static class UnityExtensions
{
    /// <summary>
    /// Run an action on all children of a gameobject
    /// </summary>
    public static void RunOnChildrenRecursive(this GameObject a_go, Action<GameObject> a_action)
    {
         foreach (var child in a_go.GetComponentsInChildren<Transform>(true))
             a_action(child.gameObject);
    }
}

To use it, do something like this: –

 myGameObject.RunOnChildrenRecursive(child => child.layer = LayerMask.NameToLayer("UI3D"));

 

 

 

 

 

 

 

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: