2016-05-13 179 views
0

我需要将特定的脚本附加到GameObject。Unity如何AddComponent <T>()?

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()>(); 

我该如何做到这一点?我有错误,谢谢。

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

+1

你的错误是什么?把它们包含在你的问题中! :) – Tom

+1

多数民众赞成不是如何泛型工作https://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx – yes

回答

2

你不能使用带有添加组件的非组件类。这意味着你的类必须从MonoBehaviour继承才能被添加到gameObject。其次,那不是你首先使用泛型的方式。如果你只是想在一个条件下为什么还要使用泛型懒得添加不同成分基地只是尝试:

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

我终于成功地做作品想要,但授予它不是一个通用的解决方案。 Chages到OP代码:

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());和它工作得很好。

+0

不明白,我需要一种方法返回一个TYPE或COMPONENT for做addComponent () – user3481415

+0

我觉得你很困惑。您不能将方法作为AddComponent的类型调用。即使你的方法返回一个Type。 –

+0

好的,那么我必须始终将组件指定给程序?该方案做出决定? – user3481415

相关问题