Guest User

Untitled

a guest
Jan 21st, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. namespace TemporalRealms.Utility {
  4.  
  5. /// <summary>
  6. /// Generic singleton base class for global, single-instance MonoBehaviors.
  7. /// </summary>
  8. /// <typeparam name="T">The class type to define</typeparam>
  9. public class SingletonMonoBehaviour<T> : MonoBehaviour where T : Component {
  10. /// <summary>
  11. /// Storage for the singleton instance.
  12. /// </summary>
  13. private static T instance;
  14.  
  15. /// <summary>
  16. /// Property that either creates or returns the existing singleton instance.
  17. /// </summary>
  18. public static T Instance {
  19. get {
  20. if (instance != null) return instance;
  21. instance = FindObjectOfType<T>();
  22. if (instance != null) return instance;
  23.  
  24. var obj = new GameObject { name = typeof(T).Name };
  25. instance = obj.AddComponent<T>();
  26. return instance;
  27. }
  28. }
  29.  
  30. /// <summary>
  31. /// Makes sure that the instance doesn't get destroyed when switching screens.
  32. /// </summary>
  33. public virtual void Awake() {
  34. if (instance == null) {
  35. instance = this as T;
  36. DontDestroyOnLoad(gameObject);
  37. } else {
  38. Destroy(gameObject);
  39. }
  40. }
  41. }
  42.  
  43. }
Add Comment
Please, Sign In to add comment