SerializedMonoSingleton.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. using System;
  6. public class SerializedMonoSingleton<T> : SerializedMonoBehaviour where T : SerializedMonoBehaviour
  7. {
  8. protected static T _insatnce;
  9. protected static object _lock = new object();
  10. public static T Instance
  11. {
  12. get
  13. {
  14. lock (_lock)
  15. {
  16. if (_insatnce == null)
  17. {
  18. var instances = FindObjectsOfType<T>();
  19. if (instances.Length > 1)
  20. {
  21. throw new Exception(string.Format("场景中存在多个类型为:{0}的脚本", typeof(T).ToString()));
  22. }
  23. else if (instances.Length == 0)
  24. {
  25. var go = new GameObject(typeof(T).ToString() + "(SerializedMonoSingleton)");
  26. _insatnce = go.AddComponent<T>();
  27. //DontDestroyOnLoad(go);
  28. }
  29. else
  30. {
  31. _insatnce = instances[0];
  32. }
  33. }
  34. return _insatnce;
  35. }
  36. }
  37. }
  38. protected virtual void OnApplicationQuit()
  39. {
  40. _insatnce = null;
  41. }
  42. protected virtual void OnDestory()
  43. {
  44. _insatnce = null;
  45. }
  46. }