【问题标题】:Getting the GameObject's Script using GetComponent by using a string of the script's name (or not)通过使用脚本名称的字符串(或不使用)使用 GetComponent 获取游戏对象的脚本
【发布时间】:2020-08-24 10:13:27
【问题描述】:

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

我所做的是:

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

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

我有一个玩家自己的脚本(用于武器控制),所以当玩家点击 LMB 时,它会得到当前持有的武器,然后得到第一个武器脚本(1st)保存其他射击技工脚本(2nd),然后运行“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


    【解决方案1】:

    有一个射击行为的中间类怎么样?

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

    【讨论】:

    • Assets\Player\Gun\WeaponScript.cs(14,26):错误 CS0506:'MakeshiftRifle.PrimaryFire()':无法覆盖继承的成员 'WeaponScript.PrimaryFire()',因为它没有被标记虚拟、抽象或覆盖 | 即使我在 WeaponScript 中有摘要。
    • 经过一番折腾后效果很好!,虽然我不知道我做了什么 lmao
    • 糟糕,是的,我添加了缺少的virtuals
    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多