ComponentSingleton.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. namespace UnityEngine.Rendering
  2. {
  3. // Use this class to get a static instance of a component
  4. // Mainly used to have a default instance
  5. /// <summary>
  6. /// Singleton of a Component class.
  7. /// </summary>
  8. /// <typeparam name="TType">Component type.</typeparam>
  9. public static class ComponentSingleton<TType>
  10. where TType : Component
  11. {
  12. static TType s_Instance = null;
  13. /// <summary>
  14. /// Instance of the required component type.
  15. /// </summary>
  16. public static TType instance
  17. {
  18. get
  19. {
  20. if (s_Instance == null)
  21. {
  22. GameObject go = new GameObject("Default " + typeof(TType).Name) { hideFlags = HideFlags.HideAndDontSave };
  23. go.SetActive(false);
  24. s_Instance = go.AddComponent<TType>();
  25. }
  26. return s_Instance;
  27. }
  28. }
  29. /// <summary>
  30. /// Release the component singleton.
  31. /// </summary>
  32. public static void Release()
  33. {
  34. if (s_Instance != null)
  35. {
  36. var go = s_Instance.gameObject;
  37. CoreUtils.Destroy(go);
  38. s_Instance = null;
  39. }
  40. }
  41. }
  42. }