WHY does Unity disallow generics use with AddComponent if it can be used elsewhere?

I’m just a little frustrated. I posted in my other thread, so far no replies.

I’ve been trying to use generics with Unity and its really tough. I can’t use the new operator with Unity, so I must use Instantiate(). Instantiate is all good and fine and all that but I can’t use generics with that either.
AddComponent() won’t allowe generics either.

What am I to do??

You can use new() and generics, you just can’t use them on a MonoBehaviour. You can use them inside a MonoBehaviour:

public class Whatever<T> {
    public T thing;
}

public WhateverWrapper : MonoBehaviour {
   private Whatever<int> stuff;

   void Start() {
       stuff = new Whatever<int>();
    }
}

or use interfaces to inherit from the generic and a MonoBehavior:

 public interface IWhatever<T> {
    public T GetThing();
}

public class WhateverString : MonoBehaviour, IWhatever<string> {
   public string GetThing() { return "Hello world"; }
}
1 Like

You can definitely use generics with AddComponent. I’ve got this extension in our project:

public static class GameObjectExtension {

    public static T EnsureComponent<T>(this GameObject go) where T : Component {
        T comp = go.GetComponent<T>();
        if(comp == null) {
            comp = go.AddComponent<T>();
        }
        return comp;
    }
}

I still have to follow the requirement that the generic value has to extend component, as you can only add Components to GameObjects.

1 Like