0

I am creating an event system for a game, I have the Abstract Class Event, and different subclasses, so far, I have made specific Methods for the creation of Each, but I would like to create them directly of their specified type

public void CreateEvent (Type t)
{
    GameObject NewEvent = new GameObject();
    NewEvent.AddComponent<t>();
}

This code gives an error message:

t is a variable but is used as a Type

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • See generics [1](https://stackoverflow.com/questions/3606595/understanding-c-sharp-generics-much-better/3606655), [2](https://stackoverflow.com/questions/77632/what-is-cool-about-generics-why-use-them) you can make your function like this `public void CreateEvent ()` and call `NewEvent.AddComponent();` – Eldar Dec 03 '19 at 17:25

1 Answers1

3

Maybe I'm making this more simple than it should be, but I think this is what you want:

public void CreateEvent<T>()
{
    GameObject NewEvent = new GameObject();
    NewEvent.AddComponent<T>();
}

But also, in keeping with standard case and naming conventions, NewEvent should really be newEvent:

public void CreateEvent<T>()
{
    GameObject newEvent = new GameObject();
    newEvent.AddComponent<T>();
}
Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • And if you really want to pass in the type bcz you cannot do generics for some reson there's an overload [`AddComponent(typeof(T))`](https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html). – user14492 Dec 03 '19 at 18:21
  • The first option didn't work, it says :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'. The second option works quite well and I will just use that one Thanks – Pablo Longobardi Dec 03 '19 at 19:34
  • @PabloLongobardi, I'm glad you got it working! The sample I gave *should* work, but it would also depend on how you are using `T` inside of `AddComponent()`. – Casey Crookston Dec 03 '19 at 19:39
  • @CaseyCrookston `AddComponent()` is [specified by Unity](https://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html) (look at the generic version, the string parameter version is deprecated). – Draco18s no longer trusts SE Dec 03 '19 at 20:27
  • @Draco18s, ah, thanks! I confess I am not familiar with Unity – Casey Crookston Dec 03 '19 at 20:29
  • That error mean yo're trying to attach something to game object that isnt' a component? Is your type derived from MB? You cannot attach anything to a gameobject. It can have unexpected issues. – user14492 Dec 04 '19 at 09:57
  • @user14492 yes, this class was derived from MB, the issue was more related to Type as a Parameter, but the solution worked just fine – Pablo Longobardi Dec 04 '19 at 13:48