Guest User

Untitled

a guest
May 20th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. /// <summary>
  4. /// A PartialMonoSingleton is like a MonoSingleton except simpler: It doesn't create itself if Instance is called and it doesn't exist.
  5. /// Instead it will return null.
  6. /// It still uses up the Awake and OnDestroy events so subclasses need to implement SubclassAwake or SubclassOnDestroy if they want to use those
  7. /// </summary>
  8. /// <typeparam name="T"></typeparam>
  9. public abstract class PartialMonoSingleton<T> : MonoBehaviour where T : PartialMonoSingleton<T> {
  10. // Query this to see if the singleton has been instantiated anywhere
  11. // NOTE: Static field in generic type - the value will be different for each inheritance of MonoSingleton
  12.  
  13. public static bool Exists = false;
  14.  
  15. public static T Instance = null;
  16.  
  17. // Assign if this is the first instance, else just show a warning that we have more than one
  18. public void Awake() {
  19. if (Instance == null) {
  20. Instance = this as T;
  21. if (Instance != null) {
  22. Exists = true;
  23. Instance.SubclassAwake();
  24. }
  25. else {
  26. Debug.LogError("PartialSingleton could not assign the instance of this class (" + typeof(T) + ")");
  27. }
  28. }
  29. else {
  30. Debug.LogWarning("Multiple instances of the PartialSingleton class " + typeof(T) + " created.");
  31. }
  32. }
  33.  
  34. protected void OnDestroy() {
  35. if (Instance != null) Instance.SubclassOnDestroy();
  36. Instance = null;
  37. Exists = false;
  38. }
  39.  
  40. // Substitute for Awake() in implementing classes
  41. protected virtual void SubclassAwake() { }
  42.  
  43. // Substitute for OnDestroy() in implementing classes
  44. protected virtual void SubclassOnDestroy() { }
  45. }
Add Comment
Please, Sign In to add comment