Unity how can AddComponent()?

2019-09-05 23:17发布

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条回答
叼着烟拽天下
2楼-- · 2019-09-05 23:51

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.

查看更多
登录 后发表回答