单例模式的实现Singleton和MonoSingleton


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// 普通单例基类
/// by:zdz
/// date:20220328
/// 
/// 
public class Singleton where T : new()
{
    private static T m_instance;
    private static readonly object locker = new object();
    public static T Instance
    {
        get
        {
            lock (locker)
            {
                if (m_instance == null) m_instance = new T();
            }
            return m_instance;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// Mono单例基类
/// by:zdz
/// date:20220328
/// 
/// 
public class MonoSingleton : MonoBehaviour where T:Component
{
    private static T m_instace;
    private static readonly object lockObj=new object();
    public static T Instance
    {
        get 
        {
            lock (lockObj)
            {
                m_instace = FindObjectOfType();
                if (m_instace == null)
                {
                    GameObject obj = new GameObject("TempObj");
                    m_instace = obj.AddComponent();
                } 
            }          
            return m_instace;
        }
    }
}