首页 > 解决方案 > 通过使用脚本名称的字符串(或不使用)使用 GetComponent 获取游戏对象的脚本

问题描述

我正在尝试制作一个枪支/武器系统,通过使用一个包含“该特定武器的射击机制”脚本而不是所有枪的一个脚本(因为我正在制作的武器有自己的特点)。

我所做的是:

基本上我有3个主要脚本,

  1. 来自玩家的作为输入的脚本(在玩家的游戏对象上
  2. 保存鼠标左右键射击机制脚本的脚本(在武器游戏对象上
  3. 执行射击机制的脚本(在武器上

我有一个玩家本身的脚本(用于武器控制),所以当玩家点击 LMB 时,它将获得它持有的当前武器,然后获得第一个武器脚本(第一个),它持有其他射击技工脚本(第二个)然后运行一个名为“LMB()”的函数,该函数在第三个脚本中运行一个函数,该函数将用于拍摄 ( 3rd )。

第一个脚本


public class PlayerShooting : MonoBehaviour
{
    public GameObject[] WeaponList;
    public int ListLength;

    public int currentWeapon;

    // Start is called before the first frame update
    void Start()
    {
        ListLength = WeaponList.Length;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            // get the 2nd script for the current weapon and runs "LMB()"
        }
    }
}

第二个脚本

    public class WeaponScript : MonoBehaviour
{
    public GameObject selfRef;
    public int WeaponId;


    public void LMB()
    {
        //I don't understand this one
        //var type = Type.GetType(WeaponId + "LMB");
        //selfRef.GetComponent(type);

        // or maybe?
        //selfRef.GetComponent<WeaponId + "LMB">().shoot();
    }
}

第三个脚本

public void shoot()
{
    //the shooting happens
}

如果让您感到困惑,我很抱歉,请随时提出问题。

标签: c#unity3d

解决方案


有一个射击行为的中级课程怎么样?

public abstract class WeaponScript : MonoBehaviour
{
    public virtual void PrimaryFire(){}
    public virtual void SecondaryFire(){}
}

然后导出例如

public class LaserScript: WeaponScript {
    public override void PrimaryFire() { /* pew pew! */ }
}

并将其连接到您的激光枪上。

然后你应该能够

if (Input.GetKeyDown(KeyCode.Mouse0)) {
    // Get the first weapon script attached to the weapon
    var weaponScript = WeaponList[currentWeapon].GetComponent<WeaponScript>();
    weaponScript.PrimaryFire();
}

推荐阅读