Skip to content

Instantly share code, notes, and snippets.

@attolee
Last active October 8, 2021 13:31
Show Gist options
  • Save attolee/92672a1ab3277e9c109224cf69cd0394 to your computer and use it in GitHub Desktop.
Save attolee/92672a1ab3277e9c109224cf69cd0394 to your computer and use it in GitHub Desktop.
traverse unity gameobject's hierarchy by recursion
/*
* https://en.wikipedia.org/wiki/Tree_(data_structure)
*/
private static List<GameObject> Traverse(GameObject parent, Type type)
{
List<GameObject> children = new List<GameObject>();
foreach (Transform node in parent.transform)
children.Add(node.gameObject);
// store target gameObjects
List<GameObject> targets = new List<GameObject>();
if (parent.GetComponent(type) != null)
targets.Add(parent);
foreach (GameObject child in children)
{
// pick out gameObject with the component
if (child.GetComponent(type) != null)
targets.Add(child);
// if child is a internal node, repeat.
if (child.transform.childCount > 0)
foreach (GameObject inn in Traverse(child, type))
if (!targets.Contains(inn))
targets.Add(inn);
}
return targets;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment