【问题标题】:NullReferenceException error in Unity when trying to get data from a static class尝试从静态类获取数据时,Unity 中出现 NullReferenceException 错误
【发布时间】:2016-02-05 14:49:08
【问题描述】:

我正在为我正在开发的本地合作游戏开发保存系统。代码的目标是建立一个可序列化的静态类,该类具有四个玩家的实例以及他们需要存储的相关数据以保存在二进制文件中。

[System.Serializable]
public class GameState  {
//Current is the GameState referenced during play
public static GameState current;
public Player mage;
public Player crusader;
public Player gunner;
public Player cleric;

public int checkPointState;

//Global versions of each player character that contains main health, second health, and alive/dead
//Also contains the checkpoint that was last activated
public GameState()
{
    mage = new Player();
    crusader = new Player();
    gunner = new Player();
    cleric = new Player();

    checkPointState = 0;
    }
}

Player 类只包含跟踪玩家统计数据的整数和一个布尔值,用于判断他们是否处于活动状态。当我在游戏场景中的一个类需要从这个静态类中获取数据时,我的问题就出现了。当引用静态类时,它会抛出错误。

    void Start () {
    mageAlive = GameState.current.mage.isAlive;
    if (mageAlive == true)
    {
        mageMainHealth = GameState.current.mage.mainHealth;
        mageSecondHealth = GameState.current.mage.secondHealth;
    } else
    {
        Destroy(this);
    }
}

我是编码新手,所以我不确定 Unity 如何与不继承自 MonoBehaviour 的静态类交互。我的这段代码基于一个工作原理非常相似的教程,所以我不确定问题是什么。

【问题讨论】:

标签: c# unity3d static nullreferenceexception serializable


【解决方案1】:

没有初始化current

一个快速的解决方案是像这样初始化current

 public static GameState current = new GameState();

这是单例模式,您可以在网上阅读有关它的信息,但 Jon Skeetthis post 是一个相当不错的起点。

我会考虑将GameState 构造函数设为私有,并将current(通常也称为Instance)设为只有getter 的属性:

private static GameState current = new GameState();
public static GameState Current 
{
    get { return current; }
}

还有很多方法可以做到这一点,特别是如果多线程是一个问题,那么你应该阅读 Jon Skeet 的帖子。

【讨论】:

    【解决方案2】:

    换个角度看:如果你想将它实现为一个静态类,那么它的工作方式会有所不同,从引用类及其数据开始,而不是以构造函数结束:

     public class GameState  {
       // not needed here, because static
       // public static GameState current;
       public static Player mage;
       public static Player crusader;
       public static Player gunner;
       [...]
       public static GameState() {
    [...]
    

    当然你的方法现在引用这个静态类的静态数据也不同了:

       void Start () {
         mageAlive = GameState.mage.isAlive;
         if (mageAlive == true) {
           mageMainHealth = GameState.mage.mainHealth;
           mageSecondHealth = GameState.mage.secondHealth;
    

    如果你想要一个(可序列化的!)单例 - 请参阅 DaveShaws answer

    【讨论】:

      猜你喜欢
      • 2022-09-24
      • 2022-01-02
      • 2019-09-03
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多