在unity中使用单例模式

using System;
using System.Collections;
using System.Collections.Generic;
namespace Victor_Wang.Utilities //可以换成你自己的命名空间
{
    public class Singleton<T> where T : class
    {
        private static volatile T _instance;//volatile可以确保_instance的读取每次都是从内存中读取而不是缓存中
        private static object lack = new object();
        protected Singleton(){ }                
        public static T Instance
    {
        get
        {
            if (_instance == null)//先判空节省性能
            {
                lock (lack)
                {
                    if (_instance == null)//确保当前线程等待锁的时候其他线程创建了实例
                    {
                        _instance = Activator.CreateInstance(typeof(T), true) as T;
                    }
                }
            }          
            return _instance;
        }
    }
        public void Destroy()
    {
        _instance = null;
    }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Victor_Wang.Utilities
{
    /// <summary>
    /// Mono单例
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        protected static T instance;
        private static readonly object locker = new object();
        private static bool _applicationIsQuitting = false;//在应用程序退出时防止创建新的单例实例
        public static T Instance
        {
            get
            {
                if (_applicationIsQuitting)
                {
                    return null;
                }
                lock (locker)
                {
                    if (instance == null)
                    {
                        instance = FindObjectOfType<T>();//遍历场景中所有的游戏对象,返回场景中T类型的第一个实例
                        if (instance == null)
                        {
                            GameObject singleton = new GameObject();
                            singleton.AddComponent<T>();
                            singleton.name = "Singleton" + typeof(T).ToString();
                            DontDestroyOnLoad(singleton);
                        }
                    }
                }
                return instance;
            }
        }

        protected virtual void Awake()
        {
            if (instance == null)
            {
                instance = this as T;
                DontDestroyOnLoad(gameObject);
            }
            else if (instance != this)
            {
                Destroy(gameObject);
            }
        }
        protected virtual void OnDestroy()
        {
            if (instance == this)
            {
                _applicationIsQuitting = true;
            }
        }
    }
}


 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值