Reputation: 36341
I have the following method:
protected T AttachComponent<T>(){
T gsComponent = gameObject.GetComponent<T>();
if(gsComponent == null){
gsComponent = gameObject.AddComponent<T>();
}
return gsComponent;
}
On the AddComponent
line I am getting the following error:
The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent()'. There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'.
I am not sure what I can do to fix this error, why Can I not do this?
Upvotes: 10
Views: 21508
Reputation: 37212
The issue is that the AddObject method returns a Component. You need to tell the compiler that your T is actually a type of Component.
Attach a generic constraint to your method, to ensure that your T
s are Component
s
protected void AttachComponent<T>() where T : Component
{
// Your code.
}
Upvotes: 25