簡體   English   中英

嘗試從靜態類獲取數據時,Unity中出現NullReferenceException錯誤

[英]NullReferenceException error in Unity when trying to get data from a static class

我正在為我正在開發的本地合作游戲開發保存系統。 該代碼的目的是建立一個Serializable Static類,該類具有四個播放器的實例以及需要存儲以保存為二進制形式的相關數據。

[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靜態類進行交互。 我是基於類似工作的教程編寫此代碼的,所以我不確定是什么問題。

初始化current沒有什么。

一種快速的解決方案是像這樣初始化current

 public static GameState current = new GameState();

這是Singleton模式,您可以在網上閱讀有關它的全部內容,但是Jon Skeet的 這篇文章是一個不錯的起點。

我考慮將GameState構造函數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;

如果您想要(可序列化!)Singleton,請參見DaveShaws答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM