Unity怎样才能AddComponent< T>()? [英] Unity how can AddComponent<T>()?
问题描述
我需要将特定脚本附加到GameObject.
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.
推荐答案
您不能将非组件类型的类与添加"组件一起使用.这意味着您的类必须继承自MonoBehaviour,才能添加到gameObject中.其次,那不是您最初如何使用泛型的方法.如果您只是想基于一个条件来添加其他组件,那么即使对泛型也感到困扰的只是尝试:
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>();
我终于设法完成了Op想要的工作,但是同意了它不是通用的解决方案. 可以选择OP代码:
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
}
}
现在您可以调用gameObject.AddComponent(ElegirScript());
,它可以正常工作.
Now you can call gameObject.AddComponent(ElegirScript());
and it works just fine.
这篇关于Unity怎样才能AddComponent< T>()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!