Advertisement
nbannister

Generic Singleton Pattern

Jan 16th, 2020
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. /// <summary>
  4. /// The Singleton pattern ensures a single class instance with global accessibility.
  5. /// Use responsibly. Most "manager" classes can be replaced by static functions in the managed class.
  6. ///
  7. /// LIMITATIONS:
  8. /// This Singleton implementaion is limited to MonoBehaviors for Unity and does not prevent multiple
  9. /// instances of a class, only how many are able to be accessed through this class.
  10. ///
  11. /// USE:
  12. /// To access your singleton call the following:
  13. ///     Singleton<ClassName>.Instance
  14. ///
  15. /// If no setup of your singleton is required ahead of time, this will be all you need, as the getter
  16. /// will create an instance. Otherwise, setup your object as required, then assign it as follows.
  17. ///
  18. /// To assign an instance as a singleton call the following when setting up your object (Start or Awake):
  19. ///     Singleton<ClassName>.Instance = this;
  20. ///
  21. /// </summary>
  22. /// <typeparam name="T"></typeparam>
  23. public class Singleton<T> where T : MonoBehaviour {
  24.     private static T instance;
  25.     public static T Instance {
  26.         //The getter will return the assigned instance, or create a new one has not been assigned.
  27.         get {
  28.             if (instance == null) {
  29.                 GameObject go = new GameObject();
  30.                 go.name = typeof(T).ToString() + "Singleton";
  31.                 instance = go.AddComponent<T>();
  32.             }
  33.             return instance;
  34.         }
  35.         //The setter will assign an instance as the singleton and destroy any pre-assigned instance.
  36.         set {
  37.             if (instance != null && instance != value) {
  38.                 GameObject.Destroy(instance);
  39.             }
  40.             instance = value;
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement