MonoSingleton.cs 1.7 KB

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