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

时间:2018-06-07 07:05:19

标签: c# arrays unity3d field abstract-class

我正在努力建立一个统一的FPS游戏,我正试图通过一个角色来实施武器装备。 为此,我有:

  • 公共抽象武器类
  • 继承自Weapon.cs的MachineGun类
  • 一个角色类,带有一系列装备好的武器

武器类:

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

机枪类:

public class MachineGun : Weapon{
    lots of machinegun code
}

在Character类中,我这样做:

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 个答案:

答案 0 :(得分:2)

我假设您将MachineGun脚本附加到GameObject 您正在尝试访问GameObject属性。你要做的就是首先获得MachineGun脚本。

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

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

Weapon weaponScript = _equipedWeapons[0].GetComponent<Weapon>();
weaponScript.
相关问题