我正在爲我正在處理的本地合作社遊戲保存系統。代碼的目標是建立一個可序列化的靜態類,它包含四個玩家的實例以及他們需要存儲以保存爲二進制文件的相關數據。嘗試從靜態類獲取數據時,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
繼承靜態類交互。我將這些代碼從基本類似的教程中取出,所以我不確定問題在哪。
請確保閱讀http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it –