- Home /
Get Component by T
How could I get all components in a generic method by T?
currently I get an error saying that T must be convertible to UnityEngine.Component. Thanks!
private List<T> GetComponent<T>(GameObjects[] objects)
{
List<T> compList = new List<T>();
foreach(GameObject o in objects)
compList.Add(o.GetComponent<T>());
return compList;
}
Answer by Kryptos · May 23, 2012 at 01:51 PM
If you also want to be able to get components by the interface(s) they implement, don't use the generic restriction but this code instead:
private List<T> GetComponent<T>(GameObjects[] objects)
{
List<T> compList = new List<T>();
foreach(GameObject o in objects)
compList.AddRange(o.GetComponents(typeof(T)));
return compList;
}
the others are right, but I think this might be more flexible for my needs. Thanks!
Yes, interfaces are quite handy ;)
Btw. I think the function should be called GetComponent*s* ;)
Very cool - I've been iterating them and using Linq - very helpful to know that...
Answer by fholm · May 23, 2012 at 12:29 PM
You're missing the "where T : UnityEngine.Component" constraint on the type parameter T.
Answer by whydoidoit · May 23, 2012 at 11:25 AM
Any script attached to a GameObject is always derived from Component. You need use a T which is a derivation of it.
What are you trying to retrieve?
Answer by lyzard · May 23, 2012 at 12:28 PM
If I understand right what you want, you need to tell explicitely that T is a subclass of MonoBehaviour, that is:
private List<T> GetComponent<T>(GameObject[] objects) where T : MonoBehaviour
I changed GameObjects by GameObject too.
This will only allow $$anonymous$$onoBehaviours to be used as generic parameter. What if you want to use "Renderer" or "Transform"
this constraint is too restrictive
Your answer
![](https://koobas.hobune.stream/wayback/20220613071832im_/https://answers.unity.com/themes/thub/images/avi.jpg)