【Unity】Синглтон в Unity

Синглтон в Unity

Синглтон

public class Singleton<T> where T : class, new()
{
    
    
    private static T _instance = null;

    private static readonly object _lock = new object();

    public static T Instance
    {
    
    
        get
        {
    
    
            lock (_lock)
            {
    
    
                if (_instance == null)
                    _instance = new T();
                return _instance;
            }
        }
    }

    protected Singleton() {
    
     }
}

МоноСинглтон

using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    
    
    private static T _instance;
    private static object _lock = new object();
    private static bool applicationIsQuitting = false;

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

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

                    if (FindObjectsOfType<T>().Length > 1)
                    {
    
    
                        Debug.LogError($"[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).ToString();
                        DontDestroyOnLoad(singleton);
                        Debug.Log($"[Singleton] An instance of { typeof(T) } is needed in the scene, so '{ singleton }' was created with DontDestroyOnLoad.");
                    }
                    else
                    {
    
    
                        Debug.Log($"[Singleton] Using instance already created: {_instance.gameObject.name}");
                    }
                }

                return _instance;
            }
        }
    }

    protected virtual void OnDestroy()
    {
    
    
        applicationIsQuitting = true;
    }

    public virtual void Awake()
    {
    
    
        if (gameObject.transform.parent == null)
            DontDestroyOnLoad(gameObject);
    }

Guess you like

Origin blog.csdn.net/TaoDuanYi/article/details/132726470