Skip to content

Instantly share code, notes, and snippets.

@blewert
Last active January 27, 2019 13:51
Show Gist options
  • Save blewert/fb63f77f90f6c54252d40b07d74f1f84 to your computer and use it in GitHub Desktop.
Save blewert/fb63f77f90f6c54252d40b07d74f1f84 to your computer and use it in GitHub Desktop.
A way to get all components in a transform, including itself & children. Unity.

Unity: Find all components of a type in an object

Tired of writing out GetComponents<Blah>() and then GetComponentsInChildren<Blah>()? Well, here are two functions which do that for you.

To use it, just shove it in some file. Then, do transform.GetAllComponents<Blah>() and voila! You have all components of this type in a nice, enumerable format.

public static class TransformExtensions
{
    public static IEnumerable<T> GetAllComponents<T>(this Transform transform)
    {
        return transform.GetComponents<T>().Union(transform.GetComponentsInChildren<T>());
    }

    public static List<T> GetAllComponentsAsList<T>(this Transform transform)
    {
        return transform.GetAllComponents<T>().ToList();
    }
}

Want to just get one component?

If you just want the first component in the parent & children, then you can add this method into the class above.

public static T GetFirstComponent<T>(this Transform transform)
{
    return transform.GetAllComponents<T>().FirstOrDefault();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment