I need to attach a specific script to a GameObject.
public T ElegirScript<T>()
{
switch((int)tipoEdificio) // enum
{
case 0:
return Edificios; // a class/script not instance
break;
case 1:
return PlantaEnergia; // a class/script not instance
break;
default:
break;
}
}
gameobject.AddComponent<ElegirScript()>();
How can I make this? I have errors, thanks.
I need first a Method that returns a type or a component, the return must be scripts. then I AddComponent and give the type the program choose, How can I do this? Examples.
You cant use a non component type class with Add component. Meaning that your class has to inherit from MonoBehaviour to be able to be added to a gameObject. And secondly thats not how you use generics in the first place. IF you just want to add a different component bases on a condition why even bother with generics just try :
I finally managed to do what Op wanted but granted its not a generic solution. Chages to OP code :
Now you can call
gameObject.AddComponent(ElegirScript());
and it works just fine.