【问题标题】:Can't access fields of the abstract class instances in an array无法访问数组中抽象类实例的字段
【发布时间】:2018-11-16 23:52:12
【问题描述】:

我正在尝试统一构建一个 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].;
}

我似乎无法了解这把机关枪的子弹数量。 事实上,我无法访问它自己的机枪字段或继承的武器字段。

【问题讨论】:

    标签: c# arrays unity3d field abstract-class


    【解决方案1】:

    我假设您已将 MachineGun 脚本附加到游戏对象。
    您正在尝试访问 GameObject 属性。你要做的就是先拿到MachineGun Script。

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

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

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

    【讨论】:

    • 你说得对,我试图访问游戏对象,而不是访问附加到游戏对象的脚本。谢谢!不过,这仍然有点令人困惑,为什么当游戏对象的字段在附加到游戏对象的机枪脚本中公开实例化时,它们无法访问?
    • 因为一个GameObject 可以有多个Components。例如,GameObject 附有 ComponentAComponentB。两个组件都可以有一个公共变量counter - 现在GameObject.counter 不清楚。
    • @Thrindil 您的脚本无法知道您是否将武器脚本附加到特定游戏对象。这就是为什么你必须告诉它,有一个武器类型的组件。您在 Unity 编辑器中构建的游戏对象和附加组件与您的 C# 代码分开
    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    相关资源
    最近更新 更多