I want to iterate through the children. From the docs it looks like one can iterate through the transforms of the children but i want to access the game objects.
If you have a reference to a Transform or any other kind of Component, you can use its .gameObject property to get at the GameObject it’s attached to:
foreach(Transform child in transform)
{
Something(child.gameObject);
}
using UnityEngine;
namespace DankoKozar.Unity.Utils
{
public class GameObjectUtil
{
public delegate void ChildHandler(GameObject child);
/// <summary>
/// Iterates all children of a game object
/// </summary>
/// <param name="gameObject">A root game object</param>
/// <param name="childHandler">A function to execute on each child</param>
/// <param name="recursive">Do it on children? (in depth)</param>
public static void IterateChildren(GameObject gameObject, ChildHandler childHandler, bool recursive)
{
DoIterate(gameObject, childHandler, recursive);
}
/// <summary>
/// NOTE: Recursive!!!
/// </summary>
/// <param name="gameObject">Game object to iterate</param>
/// <param name="childHandler">A handler function on node</param>
/// <param name="recursive">Do it on children?</param>
private static void DoIterate(GameObject gameObject, ChildHandler childHandler, bool recursive)
{
foreach (Transform child in gameObject.transform)
{
childHandler(child.gameObject);
if (recursive)
DoIterate(child.gameObject, childHandler, true);
}
}
}
}
… which is handy for executing something on all children (and the grandchildren, grandgrandchildren and so on - depending on the “recursive” parameter).