2015-11-04 103 views
0

我正在爲我正在處理的本地合作社遊戲保存系統。代碼的目標是建立一個可序列化的靜態類,它包含四個玩家的實例以及他們需要存儲以保存爲二進制文件的相關數據。嘗試從靜態類獲取數據時,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 –

回答

4

什麼都沒有初始化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的帖子。

1

爲了讓另一個角度看:如果你想實現,作爲一個靜態類,那麼這個原理不同,從引用類和它的數據,而不是用構造結束的開始:

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

相關問題