- Home /
Get components in children and childrens children and so on
I was having some trouble getting a specific component from all transforms beneath a parent object. transform.GetComponentsInChildren() only returns components of the first layer of children and not childrens children and so on.
So I wrote a small extension method. I saw a lot of posts about this so I will post my version as answer here.
Answer by michaelfelleisen · Dec 15, 2020 at 11:43 AM
Edit: Just use GetComponentsInChildren()
public static class Extension
{
public static List<T> GetComponentsInChildrenRecursively<T>(this Transform _transform, List<T> _componentList)
{
foreach (Transform t in _transform)
{
T[] components = t.GetComponents<T>();
foreach (T component in components)
{
if (component != null)
{
_componentList.Add(component);
}
}
GetComponentsInChildrenRecursively<T>(t, _componentList);
}
return _componentList;
}
}
To use this do something like this:
public Transform parent;
public void Example() {
List<Transform> transformList = new List<Transform>();
parent.GetComponentsInChildrenRecursively<Transform>(transformList);
//use transformList as you wish
}
Cheers, Michael
The documentation explicitely says:
Unity searches for components recursively on child GameObjects. This means that it also includes all the child GameObjects of the target GameObject, and all subsequent child GameObjects.
So I don't see the difference between your function and Unity's one.
If you have issues finding components on inactive gameObjects, GetComponentInChildren has a second boolean argument to include them.
You are right. I have no idea why GetComponentsInChildren did not work for my case before. Now it works completely fine.
Well, another common gotcha is that GetComponentInChildren will also include components of the given gameobject itself, not just on child objects. So it's doing the same as GetComponents but also includes components on all children. So there is a usecase for your custom implementation. However in most cases GetComponentsInChildren does work just fine.
ps: There's also a GetComponentsInParent method which also starts searching on the actual gameobject and includes all components in any parent up the hierarchy.
Your answer
Follow this Question
Related Questions
How Should I Get a List of Child Objects 2 Answers
Retrieve All Child Objects 1 Answer
Why do we access children through an object's transform? 2 Answers
How to sync child objects of a transform in multiplayer 3 Answers
FindChild/Change color 1 Answer