5

使用以下代码,我可以从“SMG”获取脚本并将其应用于武器对象:

weaponObject = GameObject.FindGameObjectWithTag(SMG).GetComponent<SMGScript>();

是否可以采取以下措施,如果可以,如何?

string variable = "SMG";

weaponObject = GameObject.FindGameObjectWithTag(variable).GetComponent<variable>();

我想要一些脚本,我可以根据变量应用于武器对象。

4

3 回答 3

4

由于我看到武器的名称与脚本不同,因此您需要 2 个变量。

string variable = "SMG";
string scriptName = "SMGScript";
GameObject.FindGameObjectWithTag(variable).GetComponent(scriptName);

这效率不高。


解决方案

你想要做的是有一个父类,你所有的武器都将从它继承。

public interface Weapon
{
}

然后你像这个例子一样创建你所有的武器:

public class M4 : MonoBehaviour, Weapon
{
}

public class MP5: MonoBehaviour, Weapon
{
}

当你想要获取脚本组件时,你可以简单地使用这个:

string tag = "Weapon";

Weapon w = GameObject.FindGameObjectWithTag(tag).GetComponent(typeof(Weapon)) as Weapon;
于 2014-08-18T13:48:16.750 回答
1

是的,可以使用变量 on GetComponent,如下所示:

weaponObject = GameObject.FindGameObjectWithTag(variable).GetComponent(variable);

即使由于性能原因不建议这样做,如here所述。

但是,我不确定您如何定义 this weaponObject,因为您从中获取的脚本GetComponent可能会有所不同,并且您的变量类型必须与您获得的脚本相同。

我的建议是将所有武器放在一个脚本中并给它一个类型变量(例如:类型 1 是机关枪,类型 2 是手枪等)来表示每种武器。这样你就可以得到上面的脚本,并通过访问类型来找出你得到的武器类型:

int weaponType = weaponObject.type;
于 2014-08-18T11:24:23.853 回答
-2

您的问题是专门询问如何在没有泛型的情况下使用 GetComponent 。在您的情况下,结果将是:

string variable = "SMG";

string scriptName = "SMGScript"

weaponObject = GameObject.FindGameObjectWithTag(variable).GetComponent(scriptName);

但一般来说,这种管理对象的方法是不可持续的。随着您的项目变得越来越大,按名称管理对象变得越来越不可行。

而且我个人强烈建议您不要使用 Enum 来表示您的武器,因为这种方法会遇到同样的问题,如果不是在更大的范围内。

听起来您想要做的是存储对 SMGScript 的引用。

最简单的方法是在脚本中创建一个字段,然后在编辑器中设置值。

如果问题是允许使用多种类型的武器,请使用继承之类的模式:

为你的武器定义一个基类:

WeaponScript : MonoBehaviour
{
   public abstract void Fire();
}

然后让 SMGScript 扩展它:

class SMGScript : WeaponScript

然后创建一个公共字段来保存武器,以便您可以在编辑器中设置它:

public WeaponScript PlayerWeapon; //The editor will let you drop *any* weapon here.

发射武器:

PlayerWeapon.Fire(); //This will let any type of weapon you set in the editor fire

要取回任何武器(尽管您可能不需要这个,见下文):

targetGameObject.GetComponent<WeaponScript>();

如果您不知道要从编辑器中获得的对象(例如,您在游戏运行时制作 SMG 对象),几乎总有更好的方法来获取参考。

例如,如果这是一个拾取器,您可以使用碰撞/触发信息来获取正确的游戏对象。

或者,如果这是一个只有一个实例的对象,但您想在运行时定义该实例,请使用 Singleton 模式。

于 2014-08-18T13:27:14.747 回答