10

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?

maccettura
  • 10,514
  • 3
  • 28
  • 35
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • you would surely do this **with an extension** in c#. Here's a tutorial for any beginners reading http://stackoverflow.com/a/35629303/294884 Hope it helps! – Fattie Mar 21 '16 at 17:51

1 Answers1

25

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.
}
RB.
  • 36,301
  • 12
  • 91
  • 131
  • 1
    That gives me this: 'GameObject' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. – Get Off My Lawn Mar 21 '16 at 17:18
  • @GetOffMyLawn Sorry, I misread your question slightly. I've updated the code in the interim to clarify my answer. Note that the constraint is now on `Component`, not `GameObject` (my mistake) – RB. Mar 21 '16 at 17:19
  • No problem! Could you please explain what the "where" part is for? – Get Off My Lawn Mar 21 '16 at 17:20
  • It's a [generic constraint](https://msdn.microsoft.com/en-us/library/d5x73970.aspx). Basically, it tells the compiler that `T` will inherit or implement `Component`, and so the compiler can treat it as a `Component`. There are a number of other constraints you can apply - check the link :) – RB. Mar 21 '16 at 17:22