MonoSingletonDontDestory.cs 1.3 KB

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