Get Components In Children

I’m writting a helper class which I will give a gameObject and it will return me an array of the children scripts of the gameObject. I can do this if I know the name of the child script. For example:

    public ChildScript[] getChildrenList(GameObject parent)
    {
      ChildScript[] array = parent.GetComponentsInChildren<ChildScript>()
    
      return array;
    }

But I want to reuse this code for many different Child Scripts. How can I make it be “generic”? If that is even possible.

	public T[] getChildrenList(GameObject parent)
	{
           T[] array =  parent.GetComponentsInChildren<T>();
		
		return array;
	}

This code produces this error: The type ‘T’ cannot be used as type parameter ‘T’ in the generic type or method ‘UnityEngine.GameObject.GetComponentsInChildren()’. There is no boxing conversion or type parameter conversion from ‘T’ to ‘UnityEngine.Component’.

The question is why do you need to write a method that already exists?

Anyway, you need to constrain the generic type T to be derived from component :

public T[] getChildrenList(GameObject parent) where T : Component

Note: If you want to be able to retrieve components based on their interface (if you use interfaces in your scripts) then you cannot use the generic version of GetComponentsInChildren but must rather use the typed version:

public T[] getChildrenList(GameObject parent)
{
    return parent.GetComponentsInChildren(typeof(T));
}