- Home /
Question by
CookieKirby · Jan 13, 2014 at 10:51 PM ·
gameobjectchildcomponentchildrenforeach
Grabbing all Children and components of those children
How could I use a foreach loop or similar to grab every child of a gameobject, and every component of those children?
Comment
Answer by KellyThomas · Jan 13, 2014 at 11:58 PM
These examples will use tranform (the current game objects transform), but can be applied to the transform of any other game object just as easily.
//Looping though the children
foreach (Transform child in transform) {
// do whatever with child
}
//Creating a list of children
Transform[] children = transform.Cast<Transform>().ToArray();
//Creating a list of components attached to the children
Component[] componentsOfChildren = transform.GetComponentsInChildren<Component>();
Note that these techniques are only searching one level deep, they would need to be applied recursively to find grandchildren etc.