Why isn't there a GetComponentsInImmediateChildren() on GameObject?

Heya,

Is there some sort of voodoo magic that I’m missing? How come you can get ALL of your children’s children, but can’t get your immediate children? Am I missing a method? I love Unity, but who implements a ‘GET ALL DESCENDENTS’ without adding a ‘GET MY IMMEDIATE CHILDREN’ method?

Thanks that make me go hmmm…

Gigiwoo.

PS - Yes, I know I can ask each child if I am their parent, but… that seems silly.

or you can loop through all children and get component for each

When life gives you lemons, make a

public static Lemonade MakeLemonade(this Lemon lemon);

(extension method)

Here’s exactly how you do it:

Put this in your extensions collection:

Note: thanks to @ArachnidAnimal below, this will absolutely match GetComponentsInChildren.

public static List<T> GetComponentsInImmediateChildren<T>(this Transform here, bool includeInactive = false) where T:MonoBehaviour
    {
    T[] tt = here.GetComponentsInChildren<T>(includeInactive);
    List<T> result = new List<T>();
    foreach (T t in tt)
        {
        if (t.transform.parent == here) result.Add(t);
        }
    return result;
    }

and then in use

foreach (Bulb b in transform.GetComponentsInImmediateChildren<Bulb>())
{
Debug.Log("b is ........ " +b.name);
}

or if needed GetComponentsInImmediateChildren(true) (exactly as you can with GetComponentsInChildren.

Thanks again to TTTTTa

Maybe not exactly how you do it. You need to take into consideration that GetComponentsInChildren only returns components in active gameobjects. Your code would return all children which are also inactive. This may or not be what the OP wants.

Edit: Just realized you bumped a 5 year old thread.

1 Like

@ArachnidAnimal is EXACTLY CORRECT - fixed! Nice call.

1 Like