Skip to content

Instantly share code, notes, and snippets.

@elmirjagudin
Created February 26, 2019 10:29
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 elmirjagudin/c6fd1c62138d901549cd045b8b8fefec to your computer and use it in GitHub Desktop.
Save elmirjagudin/c6fd1c62138d901549cd045b8b8fefec to your computer and use it in GitHub Desktop.
An example how to iterate over all Unity GameObjects in a hierarchy.
using UnityEngine;
///
/// an example how to iterate over all GameObjects in a hierarchy
///
class GameObjectsIterator
{
///
/// an example how to print root GameObject and all it's
/// children to debug console
///
public static void PrintAllObjects(GameObject root)
{
foreach (var go in AllObjects(root))
{
Debug.LogFormat("GameObject {0}", go);
}
}
///
/// makes an enumarable that contains all game objects starting with root
///
static IEnumerable<GameObject>AllObjects(GameObject root)
{
yield return root;
foreach (Transform ch in root.transform)
{
foreach (var go in AllObjects(ch.gameObject))
{
yield return go;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment