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?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With