- Home /
Get Generic Type of Component
I am trying to make an extension method for GameObject which will add a Component to that GameObject.
public static void AddUnknownComponent<T>(this GameObject gameObject){
gameObject.AddComponent<typeof(T)>();
}
However, "Only assignment call increment decrement, await, and new object expressions can be used as a statement". Any ideas on how I can get this method to work?
(I am aware of GameObject.AddComponent()...that is not what I am trying to do. Just wanted to keep out any unnecessary details from question.)
Answer by troien · Nov 15, 2014 at 07:46 PM
Get rid of the typeof ;)
And if you are using it to call AddComponent, make it so that it only accepts types that are or that inherrit from component (By adding: where T : [YourTypeHere])
Like so:
public static void AddUnknownComponent<T>(this GameObject gameObject) where T : Component
{
gameObject.AddComponent<T>();
}
For real? I have spent hours on this, and where T : Component was all that was missing? Haha! Thank you so much!
Well, actually for this error you posted, you need to get rid of the typeof.
But then you still have this error:
the type 'T' cannot be used as type parameter 'T' in the generic type method 'UnityEngine.GameObject.AddComponent()'. There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'.
For which you need to add the 'where' ;)