12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220 |
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- using UnityEngine;
- namespace QFramework
- {
- #region API
- /// <summary>
- /// Unity 游戏框架搭建 (十九) 简易对象池:http://qframework.io/post/24/ 的例子
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal class SimpleObjectPool<T> : Pool<T>
- {
- readonly Action<T> mResetMethod;
- public SimpleObjectPool(Func<T> factoryMethod, Action<T> resetMethod = null, int initCount = 0)
- {
- mFactory = new CustomObjectFactory<T>(factoryMethod);
- mResetMethod = resetMethod;
- for (int i = 0; i < initCount; i++)
- {
- mCacheStack.Push(mFactory.Create());
- }
- }
- public override bool Recycle(T obj)
- {
- if (mResetMethod != null)
- {
- mResetMethod.Invoke(obj);
- }
- mCacheStack.Push(obj);
- return true;
- }
- }
- /// <summary>
- /// Object pool.
- /// </summary>
- internal class SafeObjectPool<T> : Pool<T>, ISingleton where T : IPoolable, new()
- {
- #region Singleton
- void ISingleton.OnSingletonInit()
- {
- }
- protected SafeObjectPool()
- {
- mFactory = new DefaultObjectFactory<T>();
- }
- public static SafeObjectPool<T> Instance
- {
- get { return SingletonProperty<SafeObjectPool<T>>.Instance; }
- }
- public void Dispose()
- {
- SingletonProperty<SafeObjectPool<T>>.Dispose();
- }
- #endregion
- /// <summary>
- /// Init the specified maxCount and initCount.
- /// </summary>
- /// <param name="maxCount">Max Cache count.</param>
- /// <param name="initCount">Init Cache count.</param>
- public void Init(int maxCount, int initCount)
- {
- MaxCacheCount = maxCount;
- if (maxCount > 0)
- {
- initCount = Math.Min(maxCount, initCount);
- }
- if (CurCount < initCount)
- {
- for (var i = CurCount; i < initCount; ++i)
- {
- Recycle(new T());
- }
- }
- }
- /// <summary>
- /// Gets or sets the max cache count.
- /// </summary>
- /// <value>The max cache count.</value>
- public int MaxCacheCount
- {
- get { return mMaxCount; }
- set
- {
- mMaxCount = value;
- if (mCacheStack != null)
- {
- if (mMaxCount > 0)
- {
- if (mMaxCount < mCacheStack.Count)
- {
- int removeCount = mCacheStack.Count - mMaxCount;
- while (removeCount > 0)
- {
- mCacheStack.Pop();
- --removeCount;
- }
- }
- }
- }
- }
- }
- /// <summary>
- /// Allocate T instance.
- /// </summary>
- public override T Allocate()
- {
- var result = base.Allocate();
- result.IsRecycled = false;
- return result;
- }
- /// <summary>
- /// Recycle the T instance
- /// </summary>
- /// <param name="t">T.</param>
- public override bool Recycle(T t)
- {
- if (t == null || t.IsRecycled)
- {
- return false;
- }
- if (mMaxCount > 0)
- {
- if (mCacheStack.Count >= mMaxCount)
- {
- t.OnRecycled();
- return false;
- }
- }
- t.IsRecycled = true;
- t.OnRecycled();
- mCacheStack.Push(t);
- return true;
- }
- }
- /// <summary>
- /// Object pool 4 class who no public constructor
- /// such as SingletonClass.QEventSystem
- /// </summary>
- internal class NonPublicObjectPool<T> : Pool<T>, ISingleton where T : class, IPoolable
- {
- #region Singleton
- public void OnSingletonInit()
- {
- }
- public static NonPublicObjectPool<T> Instance
- {
- get { return SingletonProperty<NonPublicObjectPool<T>>.Instance; }
- }
- protected NonPublicObjectPool()
- {
- mFactory = new NonPublicObjectFactory<T>();
- }
- public void Dispose()
- {
- SingletonProperty<NonPublicObjectPool<T>>.Dispose();
- }
- #endregion
- /// <summary>
- /// Init the specified maxCount and initCount.
- /// </summary>
- /// <param name="maxCount">Max Cache count.</param>
- /// <param name="initCount">Init Cache count.</param>
- public void Init(int maxCount, int initCount)
- {
- if (maxCount > 0)
- {
- initCount = Math.Min(maxCount, initCount);
- }
- if (CurCount >= initCount) return;
- for (var i = CurCount; i < initCount; ++i)
- {
- Recycle(mFactory.Create());
- }
- }
- /// <summary>
- /// Gets or sets the max cache count.
- /// </summary>
- /// <value>The max cache count.</value>
- public int MaxCacheCount
- {
- get { return mMaxCount; }
- set
- {
- mMaxCount = value;
- if (mCacheStack == null) return;
- if (mMaxCount <= 0) return;
- if (mMaxCount >= mCacheStack.Count) return;
- var removeCount = mMaxCount - mCacheStack.Count;
- while (removeCount > 0)
- {
- mCacheStack.Pop();
- --removeCount;
- }
- }
- }
- /// <summary>
- /// Allocate T instance.
- /// </summary>
- public override T Allocate()
- {
- var result = base.Allocate();
- result.IsRecycled = false;
- return result;
- }
- /// <summary>
- /// Recycle the T instance
- /// </summary>
- /// <param name="t">T.</param>
- public override bool Recycle(T t)
- {
- if (t == null || t.IsRecycled)
- {
- return false;
- }
- if (mMaxCount > 0)
- {
- if (mCacheStack.Count >= mMaxCount)
- {
- t.OnRecycled();
- return false;
- }
- }
- t.IsRecycled = true;
- t.OnRecycled();
- mCacheStack.Push(t);
- return true;
- }
- }
- internal abstract class AbstractPool<T> where T : AbstractPool<T>, new()
- {
- private static Stack<T> mPool = new Stack<T>(10);
- protected bool mInPool = false;
- public static T Allocate()
- {
- var node = mPool.Count == 0 ? new T() : mPool.Pop();
- node.mInPool = false;
- return node;
- }
- public void Recycle2Cache()
- {
- OnRecycle();
- mInPool = true;
- mPool.Push(this as T);
- }
- protected abstract void OnRecycle();
- }
- #endregion
- #region interfaces
- /// <summary>
- /// 对象池接口
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal interface IPool<T>
- {
- /// <summary>
- /// 分配对象
- /// </summary>
- /// <returns></returns>
- T Allocate();
- /// <summary>
- /// 回收对象
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- bool Recycle(T obj);
- }
- /// <summary>
- /// I pool able.
- /// </summary>
- internal interface IPoolable
- {
- void OnRecycled();
- bool IsRecycled { get; set; }
- }
- /// <summary>
- /// I cache type.
- /// </summary>
- internal interface IPoolType
- {
- void Recycle2Cache();
- }
- /// <summary>
- /// 对象池
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal abstract class Pool<T> : IPool<T>
- {
- #region ICountObserverable
- /// <summary>
- /// Gets the current count.
- /// </summary>
- /// <value>The current count.</value>
- public int CurCount
- {
- get { return mCacheStack.Count; }
- }
- #endregion
- protected IObjectFactory<T> mFactory;
- /// <summary>
- /// 存储相关数据的栈
- /// </summary>
- protected readonly Stack<T> mCacheStack = new Stack<T>();
- /// <summary>
- /// default is 5
- /// </summary>
- protected int mMaxCount = 12;
- public virtual T Allocate()
- {
- return mCacheStack.Count == 0
- ? mFactory.Create()
- : mCacheStack.Pop();
- }
- public abstract bool Recycle(T obj);
- }
- #endregion
- #region DataStructurePool
- /// <summary>
- /// 字典对象池:用于存储相关对象
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- internal class DictionaryPool<TKey, TValue>
- {
- /// <summary>
- /// 栈对象:存储多个字典
- /// </summary>
- static Stack<Dictionary<TKey, TValue>> mListStack = new Stack<Dictionary<TKey, TValue>>(8);
- /// <summary>
- /// 出栈:从栈中获取某个字典数据
- /// </summary>
- /// <returns></returns>
- public static Dictionary<TKey, TValue> Get()
- {
- if (mListStack.Count == 0)
- {
- return new Dictionary<TKey, TValue>(8);
- }
- return mListStack.Pop();
- }
- /// <summary>
- /// 入栈:将字典数据存储到栈中
- /// </summary>
- /// <param name="toRelease"></param>
- public static void Release(Dictionary<TKey, TValue> toRelease)
- {
- toRelease.Clear();
- mListStack.Push(toRelease);
- }
- }
- /// <summary>
- /// 对象池字典 拓展方法类
- /// </summary>
- internal static class DictionaryPoolExtensions
- {
- /// <summary>
- /// 对字典拓展 自身入栈 的方法
- /// </summary>
- /// <typeparam name="TKey"></typeparam>
- /// <typeparam name="TValue"></typeparam>
- /// <param name="toRelease"></param>
- public static void Release2Pool<TKey, TValue>(this Dictionary<TKey, TValue> toRelease)
- {
- DictionaryPool<TKey, TValue>.Release(toRelease);
- }
- }
- /// <summary>
- /// 链表对象池:存储相关对象
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal static class ListPool<T>
- {
- /// <summary>
- /// 栈对象:存储多个List
- /// </summary>
- static Stack<List<T>> mListStack = new Stack<List<T>>(8);
- /// <summary>
- /// 出栈:获取某个List对象
- /// </summary>
- /// <returns></returns>
- public static List<T> Get()
- {
- if (mListStack.Count == 0)
- {
- return new List<T>(8);
- }
- return mListStack.Pop();
- }
- /// <summary>
- /// 入栈:将List对象添加到栈中
- /// </summary>
- /// <param name="toRelease"></param>
- public static void Release(List<T> toRelease)
- {
- toRelease.Clear();
- mListStack.Push(toRelease);
- }
- }
- /// <summary>
- /// 链表对象池 拓展方法类
- /// </summary>
- internal static class ListPoolExtensions
- {
- /// <summary>
- /// 给List拓展 自身入栈 的方法
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="toRelease"></param>
- public static void Release2Pool<T>(this List<T> toRelease)
- {
- ListPool<T>.Release(toRelease);
- }
- }
- #endregion
- #region Factories
- /// <summary>
- /// 对象工厂
- /// </summary>
- internal class ObjectFactory
- {
- /// <summary>
- /// 动态创建类的实例:创建有参的构造函数
- /// </summary>
- /// <param name="type"></param>
- /// <param name="constructorArgs"></param>
- /// <returns></returns>
- public static object Create(Type type, params object[] constructorArgs)
- {
- return Activator.CreateInstance(type, constructorArgs);
- }
- /// <summary>
- /// 动态创建类的实例:泛型扩展
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="constructorArgs"></param>
- /// <returns></returns>
- public static T Create<T>(params object[] constructorArgs)
- {
- return (T)Create(typeof(T), constructorArgs);
- }
- /// <summary>
- /// 动态创建类的实例:创建无参/私有的构造函数
- /// </summary>
- /// <param name="type"></param>
- /// <returns></returns>
- public static object CreateNonPublicConstructorObject(Type type)
- {
- // 获取私有构造函数
- var constructorInfos = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
- // 获取无参构造函数
- var ctor = Array.Find(constructorInfos, c => c.GetParameters().Length == 0);
- if (ctor == null)
- {
- throw new Exception("Non-Public Constructor() not found! in " + type);
- }
- return ctor.Invoke(null);
- }
- /// <summary>
- /// 动态创建类的实例:创建无参/私有的构造函数 泛型扩展
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns></returns>
- public static T CreateNonPublicConstructorObject<T>()
- {
- return (T)CreateNonPublicConstructorObject(typeof(T));
- }
- /// <summary>
- /// 创建带有初始化回调的 对象
- /// </summary>
- /// <param name="type"></param>
- /// <param name="onObjectCreate"></param>
- /// <param name="constructorArgs"></param>
- /// <returns></returns>
- public static object CreateWithInitialAction(Type type, Action<object> onObjectCreate,
- params object[] constructorArgs)
- {
- var obj = Create(type, constructorArgs);
- onObjectCreate(obj);
- return obj;
- }
- /// <summary>
- /// 创建带有初始化回调的 对象:泛型扩展
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="onObjectCreate"></param>
- /// <param name="constructorArgs"></param>
- /// <returns></returns>
- public static T CreateWithInitialAction<T>(Action<T> onObjectCreate,
- params object[] constructorArgs)
- {
- var obj = Create<T>(constructorArgs);
- onObjectCreate(obj);
- return obj;
- }
- }
- /// <summary>
- /// 自定义对象工厂:相关对象是 自己定义
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal class CustomObjectFactory<T> : IObjectFactory<T>
- {
- public CustomObjectFactory(Func<T> factoryMethod)
- {
- mFactoryMethod = factoryMethod;
- }
- protected Func<T> mFactoryMethod;
- public T Create()
- {
- return mFactoryMethod();
- }
- }
- /// <summary>
- /// 默认对象工厂:相关对象是通过New 出来的
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal class DefaultObjectFactory<T> : IObjectFactory<T> where T : new()
- {
- public T Create()
- {
- return new T();
- }
- }
- /// <summary>
- /// 对象工厂接口
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal interface IObjectFactory<T>
- {
- /// <summary>
- /// 创建对象
- /// </summary>
- /// <returns></returns>
- T Create();
- }
- /// <summary>
- /// 没有公共构造函数的对象工厂:相关对象只能通过反射获得
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal class NonPublicObjectFactory<T> : IObjectFactory<T> where T : class
- {
- public T Create()
- {
- var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
- var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
- if (ctor == null)
- {
- throw new Exception("Non-Public Constructor() not found! in " + typeof(T) + "\n 在没有找到非 public 的构造方法");
- }
- return ctor.Invoke(null) as T;
- }
- }
- #endregion
- #region SingletonKit For Pool
- /// <summary>
- /// 单例接口
- /// </summary>
- internal interface ISingleton
- {
- /// <summary>
- /// 单例初始化(继承当前接口的类都需要实现该方法)
- /// </summary>
- void OnSingletonInit();
- }
- /// <summary>
- /// 普通类的单例
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal abstract class Singleton<T> : ISingleton where T : Singleton<T>
- {
- /// <summary>
- /// 静态实例
- /// </summary>
- protected static T mInstance;
- /// <summary>
- /// 标签锁:确保当一个线程位于代码的临界区时,另一个线程不进入临界区。
- /// 如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放
- /// </summary>
- static object mLock = new object();
- /// <summary>
- /// 静态属性
- /// </summary>
- public static T Instance
- {
- get
- {
- lock (mLock)
- {
- if (mInstance == null)
- {
- mInstance = SingletonCreator.CreateSingleton<T>();
- }
- }
- return mInstance;
- }
- }
- /// <summary>
- /// 资源释放
- /// </summary>
- public virtual void Dispose()
- {
- mInstance = null;
- }
- /// <summary>
- /// 单例初始化方法
- /// </summary>
- public virtual void OnSingletonInit()
- {
- }
- }
- /// <summary>
- /// 属性单例类
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal static class SingletonProperty<T> where T : class, ISingleton
- {
- /// <summary>
- /// 静态实例
- /// </summary>
- private static T mInstance;
- /// <summary>
- /// 标签锁
- /// </summary>
- private static readonly object mLock = new object();
- /// <summary>
- /// 静态属性
- /// </summary>
- public static T Instance
- {
- get
- {
- lock (mLock)
- {
- if (mInstance == null)
- {
- mInstance = SingletonCreator.CreateSingleton<T>();
- }
- }
- return mInstance;
- }
- }
- /// <summary>
- /// 资源释放
- /// </summary>
- public static void Dispose()
- {
- mInstance = null;
- }
- }
- /// <summary>
- /// 普通单例创建类
- /// </summary>
- internal static class SingletonCreator
- {
- static T CreateNonPublicConstructorObject<T>() where T : class
- {
- var type = typeof(T);
- // 获取私有构造函数
- var constructorInfos = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
- // 获取无参构造函数
- var ctor = Array.Find(constructorInfos, c => c.GetParameters().Length == 0);
- if (ctor == null)
- {
- throw new Exception("Non-Public Constructor() not found! in " + type);
- }
- return ctor.Invoke(null) as T;
- }
- public static T CreateSingleton<T>() where T : class, ISingleton
- {
- var type = typeof(T);
- var monoBehaviourType = typeof(MonoBehaviour);
- if (monoBehaviourType.IsAssignableFrom(type))
- {
- return CreateMonoSingleton<T>();
- }
- else
- {
- var instance = CreateNonPublicConstructorObject<T>();
- instance.OnSingletonInit();
- return instance;
- }
- }
- /// <summary>
- /// 单元测试模式 标签
- /// </summary>
- public static bool IsUnitTestMode { get; set; }
- /// <summary>
- /// 查找Obj(一个嵌套查找Obj的过程)
- /// </summary>
- /// <param name="root">父节点</param>
- /// <param name="subPath">拆分后的路径节点</param>
- /// <param name="index">下标</param>
- /// <param name="build">true</param>
- /// <param name="dontDestroy">不要销毁 标签</param>
- /// <returns></returns>
- private static GameObject FindGameObject(GameObject root, string[] subPath, int index, bool build,
- bool dontDestroy)
- {
- GameObject client = null;
- if (root == null)
- {
- client = GameObject.Find(subPath[index]);
- }
- else
- {
- var child = root.transform.Find(subPath[index]);
- if (child != null)
- {
- client = child.gameObject;
- }
- }
- if (client == null)
- {
- if (build)
- {
- client = new GameObject(subPath[index]);
- if (root != null)
- {
- client.transform.SetParent(root.transform);
- }
- if (dontDestroy && index == 0 && !IsUnitTestMode)
- {
- GameObject.DontDestroyOnLoad(client);
- }
- }
- }
- if (client == null)
- {
- return null;
- }
- return ++index == subPath.Length ? client : FindGameObject(client, subPath, index, build, dontDestroy);
- }
- /// <summary>
- /// 泛型方法:创建MonoBehaviour单例
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <returns></returns>
- public static T CreateMonoSingleton<T>() where T : class, ISingleton
- {
- T instance = null;
- var type = typeof(T);
- //判断T实例存在的条件是否满足
- if (!IsUnitTestMode && !Application.isPlaying)
- return instance;
- //判断当前场景中是否存在T实例
- instance = UnityEngine.Object.FindObjectOfType(type) as T;
- if (instance != null)
- {
- instance.OnSingletonInit();
- return instance;
- }
- //MemberInfo:获取有关成员属性的信息并提供对成员元数据的访问
- MemberInfo info = typeof(T);
- //获取T类型 自定义属性,并找到相关路径属性,利用该属性创建T实例
- var attributes = info.GetCustomAttributes(true);
- foreach (var atribute in attributes)
- {
- var defineAttri = atribute as MonoSingletonPath;
- if (defineAttri == null)
- {
- continue;
- }
- instance = CreateComponentOnGameObject<T>(defineAttri.PathInHierarchy, true);
- break;
- }
- //如果还是无法找到instance 则主动去创建同名Obj 并挂载相关脚本 组件
- if (instance == null)
- {
- var obj = new GameObject(typeof(T).Name);
- if (!IsUnitTestMode)
- UnityEngine.Object.DontDestroyOnLoad(obj);
- instance = obj.AddComponent(typeof(T)) as T;
- }
- instance.OnSingletonInit();
- return instance;
- }
- /// <summary>
- /// 在GameObject上创建T组件(脚本)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="path">路径(应该就是Hierarchy下的树结构路径)</param>
- /// <param name="dontDestroy">不要销毁 标签</param>
- /// <returns></returns>
- private static T CreateComponentOnGameObject<T>(string path, bool dontDestroy) where T : class
- {
- var obj = FindGameObject(path, true, dontDestroy);
- if (obj == null)
- {
- obj = new GameObject("Singleton of " + typeof(T).Name);
- if (dontDestroy && !IsUnitTestMode)
- {
- UnityEngine.Object.DontDestroyOnLoad(obj);
- }
- }
- return obj.AddComponent(typeof(T)) as T;
- }
- /// <summary>
- /// 查找Obj(对于路径 进行拆分)
- /// </summary>
- /// <param name="path">路径</param>
- /// <param name="build">true</param>
- /// <param name="dontDestroy">不要销毁 标签</param>
- /// <returns></returns>
- private static GameObject FindGameObject(string path, bool build, bool dontDestroy)
- {
- if (string.IsNullOrEmpty(path))
- {
- return null;
- }
- var subPath = path.Split('/');
- if (subPath == null || subPath.Length == 0)
- {
- return null;
- }
- return FindGameObject(null, subPath, 0, build, dontDestroy);
- }
- }
- /// <summary>
- /// 静态类:MonoBehaviour类的单例
- /// 泛型类:Where约束表示T类型必须继承MonoSingleton<T>
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal abstract class MonoSingleton<T> : MonoBehaviour, ISingleton where T : MonoSingleton<T>
- {
- /// <summary>
- /// 静态实例
- /// </summary>
- protected static T mInstance;
- /// <summary>
- /// 静态属性:封装相关实例对象
- /// </summary>
- public static T Instance
- {
- get
- {
- if (mInstance == null && !mOnApplicationQuit)
- {
- mInstance = SingletonCreator.CreateMonoSingleton<T>();
- }
- return mInstance;
- }
- }
- /// <summary>
- /// 实现接口的单例初始化
- /// </summary>
- public virtual void OnSingletonInit()
- {
- }
- /// <summary>
- /// 资源释放
- /// </summary>
- public virtual void Dispose()
- {
- if (SingletonCreator.IsUnitTestMode)
- {
- var curTrans = transform;
- do
- {
- var parent = curTrans.parent;
- DestroyImmediate(curTrans.gameObject);
- curTrans = parent;
- } while (curTrans != null);
- mInstance = null;
- }
- else
- {
- Destroy(gameObject);
- }
- }
- /// <summary>
- /// 当前应用程序是否结束 标签
- /// </summary>
- protected static bool mOnApplicationQuit = false;
- /// <summary>
- /// 应用程序退出:释放当前对象并销毁相关GameObject
- /// </summary>
- protected virtual void OnApplicationQuit()
- {
- mOnApplicationQuit = true;
- if (mInstance == null) return;
- Destroy(mInstance.gameObject);
- mInstance = null;
- }
- /// <summary>
- /// 释放当前对象
- /// </summary>
- protected virtual void OnDestroy()
- {
- mInstance = null;
- }
- /// <summary>
- /// 判断当前应用程序是否退出
- /// </summary>
- public static bool IsApplicationQuit
- {
- get { return mOnApplicationQuit; }
- }
- }
- /// <summary>
- /// MonoSingleton路径
- /// </summary>
- [AttributeUsage(AttributeTargets.Class)] //这个特性只能标记在Class上
- internal class MonoSingletonPath : Attribute
- {
- private string mPathInHierarchy;
- public MonoSingletonPath(string pathInHierarchy)
- {
- mPathInHierarchy = pathInHierarchy;
- }
- public string PathInHierarchy
- {
- get { return mPathInHierarchy; }
- }
- }
- /// <summary>
- /// 继承Mono的属性单例?
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal static class MonoSingletonProperty<T> where T : MonoBehaviour, ISingleton
- {
- private static T mInstance;
- public static T Instance
- {
- get
- {
- if (null == mInstance)
- {
- mInstance = SingletonCreator.CreateMonoSingleton<T>();
- }
- return mInstance;
- }
- }
- public static void Dispose()
- {
- if (SingletonCreator.IsUnitTestMode)
- {
- UnityEngine.Object.DestroyImmediate(mInstance.gameObject);
- }
- else
- {
- UnityEngine.Object.Destroy(mInstance.gameObject);
- }
- mInstance = null;
- }
- }
- /// <summary>
- /// 如果跳转到新的场景里已经有了实例,则不创建新的单例(或者创建新的单例后会销毁掉新的单例)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal abstract class PersistentMonoSingleton<T> : MonoBehaviour where T : Component
- {
- protected static T mInstance;
- protected bool mEnabled;
- /// <summary>
- /// Singleton design pattern
- /// </summary>
- /// <value>The instance.</value>
- public static T Instance
- {
- get
- {
- if (mInstance == null)
- {
- mInstance = FindObjectOfType<T>();
- if (mInstance == null)
- {
- var obj = new GameObject();
- mInstance = obj.AddComponent<T>();
- }
- }
- return mInstance;
- }
- }
- /// <summary>
- /// On awake, we check if there's already a copy of the object in the scene. If there's one, we destroy it.
- /// </summary>
- protected virtual void Awake()
- {
- if (!Application.isPlaying)
- {
- return;
- }
- if (mInstance == null)
- {
- //If I am the first instance, make me the Singleton
- mInstance = this as T;
- DontDestroyOnLoad(transform.gameObject);
- mEnabled = true;
- }
- else
- {
- //If a Singleton already exists and you find
- //another reference in scene, destroy it!
- if (this != mInstance)
- {
- Destroy(this.gameObject);
- }
- }
- }
- }
- /// <summary>
- /// 如果跳转到新的场景里已经有了实例,则删除已有示例,再创建新的实例
- /// </summary>
- /// <typeparam name="T"></typeparam>
- internal class ReplaceableMonoSingleton<T> : MonoBehaviour where T : Component
- {
- protected static T mInstance;
- public float InitializationTime;
- /// <summary>
- /// Singleton design pattern
- /// </summary>
- /// <value>The instance.</value>
- public static T Instance
- {
- get
- {
- if (mInstance == null)
- {
- mInstance = FindObjectOfType<T>();
- if (mInstance == null)
- {
- GameObject obj = new GameObject();
- obj.hideFlags = HideFlags.HideAndDontSave;
- mInstance = obj.AddComponent<T>();
- }
- }
- return mInstance;
- }
- }
- /// <summary>
- /// On awake, we check if there's already a copy of the object in the scene. If there's one, we destroy it.
- /// </summary>
- protected virtual void Awake()
- {
- if (!Application.isPlaying)
- {
- return;
- }
- InitializationTime = Time.time;
- DontDestroyOnLoad(this.gameObject);
- // we check for existing objects of the same type
- T[] check = FindObjectsOfType<T>();
- foreach (T searched in check)
- {
- if (searched != this)
- {
- // if we find another object of the same type (not this), and if it's older than our current object, we destroy it.
- if (searched.GetComponent<ReplaceableMonoSingleton<T>>().InitializationTime < InitializationTime)
- {
- Destroy(searched.gameObject);
- }
- }
- }
- if (mInstance == null)
- {
- mInstance = this as T;
- }
- }
- }
- #endregion
- }
|