12345678910111213141516171819202122232425262728293031323334353637383940 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- namespace TFramework
- {
- /// <summary>
- /// Mono单例模式基类
- /// </summary>
- /// <typeparam name="T"></typeparam>
- [DisallowMultipleComponent]
- [DefaultExecutionOrder(-10000)]
- public class SingletonBehaviourBase<T> : MonoBehaviour where T : MonoBehaviour
- {
- public bool doNotDestroy;
- private static T _instance;
- /// <summary>
- /// 当前实例
- /// </summary>
- public static T Instance => _instance;
- protected virtual void Awake()
- {
- if (_instance == null)
- _instance = GetComponent<T>();
- else
- throw new UnityException($"单例类【{typeof(T).FullName}】发现两个或以上实例,这是不被允许的!");
- if (doNotDestroy&&_instance!=null)
- {
- DontDestroyOnLoad(gameObject);
- }
- }
- protected virtual void OnDestroy() => _instance = null;
- }
- }
|