Unity如何添加组件<t>()?

时间:2016-05-13 10:01:26

标签: c# methods unity3d

我需要将特定脚本附加到GameObject。

resources :recipes

我该怎么做?我有错误,谢谢。

我首先需要一个返回类型或组件的方法,返回必须是脚本。然后我AddComponent并给出程序选择的类型,我该怎么做?实例

1 个答案:

答案 0 :(得分:2)

您无法使用添加组件的非组件类型类。这意味着您的类必须从MonoBehaviour继承才能添加到gameObject。其次,这不是你如何首先使用泛型。如果你只想添加一个不同的组件基于条件,为什么甚至打扰泛型只是尝试:

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

我终于设法做了Op想要的但却授予它不是通用的解决方案。 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
        }
    }

现在你可以致电gameObject.AddComponent(ElegirScript());,它运作正常。