2017-10-04 103 views
-3

我真的很笨,但我認爲我是雪盲。從另一個優雅的調用中,我無法訪問單例類方法。我得到了可怕的訪問一個單例返回(NullReferenceException)

(NullReferenceException)。

這裏是我的簡單單身人士,以及我如何調用方法。

public class PlayerNodePosition : MonoBehaviour 
{ 

public static PlayerNodePosition instance; 

string code; 

void Awake() 
{ 
    if (instance == null) 
    { 
     Debug.LogWarning("More than one instance of Inventory found!"); 
     return; 
    } 

    instance = this; 
} 

public void AddCode(string _code) 
{ 
    code = _code; 
} 
} 

這裏是來自另一個腳本的調用者。

void AddCode() 
{ 

    PlayerNodePosition.instance.AddCode("Added!"); 

} 

是一個「傻瓜」我很明顯缺少明顯的。

+0

除了答案,你可能會發現這篇文章:http://www.c-sharpcorner.com/UploadFile/8911c4/singleton-design-pattern-in-C-Sharp /有用的 – 4D1C70

回答

0

方法Awake應該是靜態的,並且應該設置實例。我沒有機會檢查這是否運行,因爲我沒有安裝C#,但是您提供的調試日誌警告在邏輯上是錯誤的。如果沒有實例,則需要創建一個實例。如果有實例,則返回該實例。這是單身模式。

public class PlayerNodePosition : MonoBehaviour 
{ 
    public static PlayerNodePosition instance; 

    string code; 

    void static getInstance() 
    { 
     if (instance == null) 
     { 
      instance = new PlayerNodePosition(); 
     } 

     return instance; 
    } 

    public void AddCode(string _code) 
    { 
     code = _code; 
    } 
} 
+0

神話般的,謝謝你的職位。我可以看到我缺少的東西。 – Wizz69

1

你不要實例instance任何地方。你需要類似

private static PlayerNodePosition playerNodePosition; 
public static PlayerNodePosition instance 
{ 
    get 
    { 
     if (playerNodePosition == null) { 
      playerNodePosition = new PlayerNodePosition(); 
     } 
     return playerNodePosition; 
    } 
} 
+0

謝謝你Svet,我看到了我的方式的錯誤。 – Wizz69