Unity how can AddComponent<T>()?

眉间皱痕 提交于 2019-12-12 03:27:33

问题


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.


回答1:


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 :

if(condition)
gameObject.AddComponent<MyMonoBehaviourClass1>();
else
gameObject.AddComponent<MyMonoBehaviourClass2>();

I finally managed to do what Op wanted but granted its not a generic solution. Chages to OP code :

public Type ElegirScript()
    {
        switch ((int)tipoEdificio)  // enum
        {
            case 0:
                return typeof(Edificios);  // a class/script not instance
            case 1:
                return typeof(PlantaEnergia);  // a class/script not instance
            default:
                return null;//Or throw exception here
        }
    }

Now you can call gameObject.AddComponent(ElegirScript()); and it works just fine.



来源:https://stackoverflow.com/questions/37207045/unity-how-can-addcomponentt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!