Unity 框架

SingletonBehaviourBase.cs 1016B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TFramework
  5. {
  6. /// <summary>
  7. /// Mono单例模式基类
  8. /// </summary>
  9. /// <typeparam name="T"></typeparam>
  10. [DisallowMultipleComponent]
  11. [DefaultExecutionOrder(-10000)]
  12. public class SingletonBehaviourBase<T> : MonoBehaviour where T : MonoBehaviour
  13. {
  14. public bool doNotDestroy;
  15. private static T _instance;
  16. /// <summary>
  17. /// 当前实例
  18. /// </summary>
  19. public static T Instance => _instance;
  20. protected virtual void Awake()
  21. {
  22. if (_instance == null)
  23. _instance = GetComponent<T>();
  24. else
  25. throw new UnityException($"单例类【{typeof(T).FullName}】发现两个或以上实例,这是不被允许的!");
  26. if (doNotDestroy&&_instance!=null)
  27. {
  28. DontDestroyOnLoad(gameObject);
  29. }
  30. }
  31. protected virtual void OnDestroy() => _instance = null;
  32. }
  33. }