[Unity] Singleton Pattern with MonoBehaviour



使用方法

1. 掛在某個 GameObject 上
2. 完全沒掛 GameObject,呼叫 Class.Instance 就會直接產生

public class SingletonClass : Singleton<SingletonClass>
{
    public void Initialize()
    {
        //...
    }
}

public class Main : Monobehaviour
{
    void Start()
    {
        SingletonClass.Instance.Initialize();
    }
}
Source Code
    public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        [SerializeField]
        private bool IS_DEBUG_LOG = false;

        private static T _instance;
        private static object _lock = new object();

        public static T Instance
        {
            get
            {
                if ( applicationIsQuitting )
                {
                    DebugLog( "[Singleton] Instance '" + typeof( T ) +
                        "' already destroyed on application quit." +
                        " Won't create again - returning null." );
                    return null;
                }

                lock ( _lock )
                {
                    if ( _instance == null )
                    {
                        _instance = ( T ) FindObjectOfType( typeof( T ) );

                        if ( FindObjectsOfType( typeof( T ) ).Length > 1 )
                        {
                            DebugLog( "[Singleton] Something went really wrong " +
                                " - there should never be more than 1 singleton!" +
                                " Reopenning the scene might fix it." );
                            return _instance;
                        }

                        if ( _instance == null )
                        {
                            GameObject singleton = new GameObject();
                            _instance = singleton.AddComponent<T>();
                            singleton.name = "(singleton) " + typeof( T ).Name.ToString();

                            DontDestroyOnLoad( singleton );

                            DebugLog( "[Singleton] An instance of " + typeof( T ) +
                                " is needed in the scene, so '" + singleton +
                                "' was created with DontDestroyOnLoad." );
                        }
                        else
                        {
                            DebugLog( "[Singleton] Using instance already created: " +
                                _instance.gameObject.name );
                        }
                    }

                    return _instance;
                }
            }
        }

        private static void DebugLog( string log )
        {
            if ( IS_DEBUG_LOG )
            {
                Debug.Log( log );
            }
        }

        private static bool applicationIsQuitting = false;
        public void OnDestroy()
        {
            applicationIsQuitting = true;
        }
    }



歡迎您留言與分享!(Welcome for comments or sharing!)

Related Post:

Tagged on: