Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type 'T' cannot be used as type parameter 'T' in the generic type or method

Tags:

c#

unity3d

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?

like image 491
Get Off My Lawn Avatar asked Mar 21 '16 17:03

Get Off My Lawn


1 Answers

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 Ts are Components

protected void AttachComponent<T>() where T : Component
{
    // Your code.
}
like image 85
RB. Avatar answered Oct 16 '22 19:10

RB.