Get Off My Lawn
Get Off My Lawn

Reputation: 36341

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

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

Answers (1)

RB.
RB.

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

protected void AttachComponent<T>() where T : Component
{
    // Your code.
}

Upvotes: 25

Related Questions