代码之家  ›  专栏  ›  技术社区  ›  Thrindil

无法访问数组中抽象类实例的字段

  •  0
  • Thrindil  · 技术社区  · 6 年前

    我想在Unity中建立一个FPS游戏,我想用一个角色来实现武器装备。 为此,我有:

    • 公共抽象武器类
    • 继承自weapon.cs的machinegun类
    • 有一系列装备武器的角色类

    武器等级:

    public abstract class Weapon : MonoBehaviour { 
        lots of weapon code
    }
    

    机枪等级:

    public class MachineGun : Weapon{
        lots of machinegun code
    }
    

    在角色类中,我这样做:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    //keeps track of all the character properties
    public class Character : MonoBehaviour {
    
         public GameObject[] _equipedWeapons = new GameObject[10];     //an array of all the weapons a character has
    
    private void Start()
    {
        _equipedWeapons = new GameObject[10];                               //size of the weapons array, TEMP 10
        _equipedWeapons[0] = new GameObject();
        _equipedWeapons[0] = GameObject.FindWithTag("Weapon0");
    }
    

    这就是我的问题所在:

    public void IncreaseBullets(int amount)
    {
        _equipedWeapons[0].;
    }
    

    我好像看不到这个机关枪有多少子弹。 事实上,我不能进入它自己的机枪场,或者继承的武器场。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Sebastian Kilb    6 年前

    我想你已经把machinegun脚本附加到gameobject上了。
    您正在尝试访问gameobject属性。你要做的是先拿到机枪脚本。

    MachineGun weaponScript = _equipedWeapons[0].GetComponent<MachineGun>();
    weaponScript.
    

    你也可以得到这样的武器脚本。当你想用同样的方法访问不同的武器类型时。

    Weapon weaponScript = _equipedWeapons[0].GetComponent<Weapon>();
    weaponScript.