Skip to content

Instantly share code, notes, and snippets.

@pinkas
Last active February 12, 2022 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinkas/ad12449d59ddec31e56c4a986f036edf to your computer and use it in GitHub Desktop.
Save pinkas/ad12449d59ddec31e56c4a986f036edf to your computer and use it in GitHub Desktop.
Recursive free way to traverse through ALL the child game objects of a parent
public static void Traverse(GameObject gameObject, Action<GameObject> action)
{
if (gameObject == null)
{
throw new ArgumentNullException("gameObject");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
Stack<Transform> stack = new Stack<Transform>();
stack.Push(gameObject.transform);
while (stack.Count > 0)
{
Transform node = stack.Pop();
action(node.gameObject);
for (int i = 0; i < node.childCount; ++i)
{
stack.Push(node.GetChild(i));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment