MonoBehaviour的單例模式

轉載自:https://blog.csdn.net/smilelance/article/details/7839878

我們有一個繼承自MonoBehaviour的類是用來做對象交互動作的,想做成單例的,寫成通用的方法報錯。

private static Communication instance;
    public static Communication GetInstance()
    {
      if(instance==null){
        instance=new Communication();
        }
        return instance;
    }

提示:You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent().  Alternatively, your script can inherit from ScriptableObject or no base class at all

網上找到了解決方案,系統會自動創建MonoBehaviour 對象,在其awake時候設置其instane即可。

正確代碼如下:

private static Communication instance;
    public static Communication GetInstance()
    {
        return instance;
    }


void Awake() {
instance = this;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章