前往
大廳
主題

【Unity紀錄】在Unity中的Singleton Pattern

高雄鐵道具象 | 2021-06-16 14:27:40 | 巴幣 100 | 人氣 1704

最近不論是在工作中抑或是自主開發的專案中,總是會時常的運用到Design Pattern中的Singleton (單例模式),故此就花點時間記錄下一些關於Singleton的觀念和運用,而這邊就只簡單的紀錄有用過的c#、MonoBehaviourSingleton

1.什麼是Singleton Pattern

簡單來說Singleton Pattern(單例模式),就是在運行環境中,只有一個instance存在;
使用時,代碼只需要調用 SingletonClass.Instance.Something() 來進行;
遊戲例子:

  • testClass.Instance.SaveBestScore(123)   → 保存
  • testClass.Instance.GetBestScore()           → 獲取
使用單例令一個好處,我們只在頭一個instance進行初始化(比較慢的邏輯),不用每次的進行初始邏輯(如上面的例子,省卻Load Best Score的邏輯);
另外,切換Scene後,也能保存某些狀態或是數據。

2.C# Class的Singleton
private static testClass instance;
public static testClass Instance()
    {
        return instance;
    }

優點:
簡單,方便移植,不需要依賴Unity相關的物件;而之後提及的Singleton,其實也是基於這裡的邏輯。
缺點:
不能進行File IO,也沒有MonoBehaviour的Update/FixUpdate,也不能在inspector/Hierarchy View看到;

2.C# Class的Singleton
private static TestClass getInstance;
public static testClass GetInstance
{
        get
        {
            if (getInstance == null)
            {
                getInstance = FindObjectOfType(typeof(Enemy)) as Enemy;
                if (getInstance == null)
                {
                    GameObject go = new GameObject("Enemy");
                    getInstance = go.AddComponent<Enemy>();
                }
            }
            return getInstance;
        }
    }

  • 支持Update/FixUpdate那些,所以Singleton能按時間段做一些邏輯;
  • 可以在Hierarchy View內,找到相關Singleton;
  • 可以放到Scene或Prefab,並且利用inspector設定Singleton的屬性;
如果是有繼承到MonoBehaviour的class,就必須要使用這個方式的Singleton,否則是會有錯誤的。

如果有錯歡迎指證。

創作回應

更多創作