Last active
October 8, 2021 13:31
-
-
Save attolee/92672a1ab3277e9c109224cf69cd0394 to your computer and use it in GitHub Desktop.
traverse unity gameobject's hierarchy by recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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