- Home /
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'.
Answer by Kryptos · Nov 08, 2012 at 09:34 AM
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));
}
I want to say: Find me all the Children inside this gameObject and not tell it what the children are.
This answer is missing the generic parameter ;)
public T[] getChildrenList(GameObject parent) where T : Component
Anyway, like $$anonymous$$ryptos said this function does EXECTLY the same as GetComponentsInChildren, so i'm also not sure what's the purpose of this function. Can you be a bit more specific what you want to do?
You are both right, it is the same function. I want a function that I tell it, Find me all the Children-Scripts inside this gameObject and I don't have to say the children names.
But that's just GetComponentsInChildren (except the it also returns those scripts on the parent too)...
Your answer
![](https://koobas.hobune.stream/wayback/20220613083529im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
get component type at runtime using generic GetComponent in C# 1 Answer
Generic Component Declaration 1 Answer
A generic "Find GameObject From Path" method. 2 Answers
How to Access Components in Children of GameObject? 1 Answer
GameObject info 2 Answers