SingletonMono.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. namespace SC.XR.Unity
  8. {
  9. public abstract class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour
  10. {
  11. private static T instance;
  12. private static object lockObj = new object();
  13. public static T Instance
  14. {
  15. get
  16. {
  17. if (instance == null)
  18. {
  19. instance = (T)FindObjectOfType(typeof(T));
  20. if (instance == null)
  21. {
  22. lock (lockObj)
  23. {
  24. if (instance == null)
  25. {
  26. GameObject singleton = new GameObject();
  27. instance = singleton.AddComponent<T>();
  28. singleton.name = "(Singleton) " + typeof(T).Name;
  29. DontDestroyOnLoad(singleton);
  30. }
  31. }
  32. }
  33. }
  34. return instance;
  35. }
  36. }
  37. }
  38. }