Unity实用单例 and MonoBehaviour单例

拷贝即用:
单例:

public class SingletonBase<T> where T : class, new()
{
    private static T m_instance;
    
    public static T Instance {
        get {
            if (m_instance == null)
            {
                // 若T class具有私有构造函数,那么则无法使用SingletonProvider<T>来实例化new T();
                m_instance = new T();
            }
            return m_instance;
        }
        set { m_instance = value; }
    }
}

MonoBehaviour单例:

using UnityEngine;

public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : SingletonMonoBehaviour<T>
{
    protected static T sInstance = null;
    protected static bool IsCreate = false;
 
    public static T Instance
    {
        get
        {
            CreateInstance();
            return sInstance;
        }
    }
 
    protected virtual void Awake()
    {
        if (sInstance == null)
        {
            sInstance = this as T;
            IsCreate = true;
 
            Init();
        }
    }
 
    public static bool InstanceIsNull()
    {
        return sInstance == null;
    }
 
    protected virtual void Init()
    {
    }
 
    protected virtual void OnDestroy()
    {
        sInstance = null;
        IsCreate = false;
    }
 
    public static void CreateInstance()
    {
        if (IsCreate)
            return;
 
        IsCreate = true;
        T[] managers = FindObjectsOfType(typeof(T)) as T[];
        if (managers.Length != 0)
        {
            if (managers.Length == 1)
            {
                sInstance = managers[0];
                sInstance.gameObject.name = typeof(T).Name;
                DontDestroyOnLoad(sInstance.gameObject);
                return;
            }
            else
            {
                foreach (T manager in managers)
                {
                    Destroy(manager.gameObject);
                }
            }
        }
 
        GameObject obj = new GameObject(typeof(T).Name, typeof(T));
        sInstance = obj.GetComponent<T>();
        DontDestroyOnLoad(sInstance.gameObject);
    }
 
    public static void ReleaseInstance()
    {
        if (sInstance != null)
        {
            Destroy(sInstance.gameObject);
            sInstance = null;
            IsCreate = false;
        }
    }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值