尝试从静态类获取数据时,Unity中出现NullReferenceException错误

问题描述:

我正在为我正在处理的本地合作社游戏保存系统。代码的目标是建立一个可序列化的静态类,它包含四个玩家的实例以及他们需要存储以保存为二进制文件的相关数据。尝试从静态类获取数据时,Unity中出现NullReferenceException错误

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

我是新来的编码,所以我不知道如何团结与不从MonoBehaviour继承静态类交互。我将这些代码从基本类似的教程中取出,所以我不确定问题在哪。

+0

请确保阅读http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it –

什么都没有初始化current

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

public static GameState current = new GameState(); 

这是Singleton模式,你可以看到一个关于它的所有网站上,但this post通过Jon Skeet是一个相当不错的开端。

我会考虑做GameState构造私人,并使current(又名Instance正常)到属性只有一个getter:

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

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

为了让另一个角度看:如果你想实现,作为一个静态类,那么这个原理不同,从引用类和它的数据,而不是用构造结束的开始:

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