うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Singleton な MonoBehaviour

デザインパターンの一つである Singleton パターン を利用した MonoBehaviour

実行優先度を上げるために DefaultExecutionOrder で -1 を指定している

利用するときは public class SingletonSample : Singleton<SingletonSample> のようにして作成し

SingletonSample.I.Value で操作できる

using UnityEngine;
 
public class SingletonSample : Singleton<SingletonSample>
{
    public int Value;
}
using UnityEngine;
 
[DefaultExecutionOrder(-1)]
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    public static T I { get; private set; }

    private void Awake()
    {
        if (!I.IsNull())
            return;

        I = this as T;
        I.Init();
    }
  
    protected virtual void Init()
    {
    }
 
    public static bool IsExist()
    {
        return I != null;
    }
 
    protected static bool CreateInstance(Transform parent = null)
    {
        if (IsExist())
            return false;
        
        GameObject obj = new GameObject(typeof(T).Name, typeof(T));
        if (parent != null)
            obj.transform.SetParent(parent);
        else
            DontDestroyOnLoad(obj);
 
        return true;
    }
}