- g UnityEngine;
- using System.Collections;
- namespace SingleTonBases
- {
- #region 不继承Mono
- /// <summary>
- /// 不继承自Mono的单例1
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public class SingleTonBase<T> where T : new()
- {
- private static T _instance;
- public static T Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = new T();
- }
- return _instance;
- }
- }
- }
- /// <summary>
- /// 不继承自Mono的单例2
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public abstract class Singleton<T> : System.IDisposable where T : new()
- {
- private static T instance;
- public static T Instance
- {
- get
- {
- if (instance == null)
- {
- instance = new T();
- }
- return instance;
- }
- }
- public virtual void Dispose()
- {
- }
- }
- #endregion
- #region 继承Mono
- /// <summary>
- /// 继承自Mono的单例
- /// 可挂可不挂在游戏物体上
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public abstract class MonoSingleTon<T> : MonoBehaviour where T : MonoBehaviour
- {
- private static T _instance;
- public static T Instance
- {
- get
- {
- if (_instance == null)
- {
- GameObject obj = new GameObject(typeof(T).Name);
- _instance = obj.AddComponent<T>();
- }
- return _instance;
- }
- }
- /// <summary>
- /// 可重写的虚方法,用于实例化对象
- /// </summary>
- protected virtual void Awake()
- {
- _instance = this as T;
- }
- }
- /// <summary>
- /// 继承自Mono的单例
- /// 可挂可不挂在游戏物体上
- /// 跳转场景不销毁对象(DontDestroyOnLoad)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public class MonoSingleTonDontDestroyOnLoad<T> : MonoBehaviour where T : MonoBehaviour
- {
- private static T _instance;
- public static T Instance
- {
- get
- {
- if (_instance == null)
- {
- GameObject obj = new GameObject(typeof(T).Name);
- _instance = obj.AddComponent<T>();
- }
- return _instance;
- }
- }
- /// <summary>
- /// 可重写的虚方法,用于实例化对象
- /// </summary>
- protected virtual void Awake()
- {
- _instance = this as T;
- DontDestroyOnLoad(this);
- }
- }
- #endregion
- }