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.


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