Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- /// <summary>
- /// The Singleton pattern ensures a single class instance with global accessibility.
- /// Use responsibly. Most "manager" classes can be replaced by static functions in the managed class.
- ///
- /// LIMITATIONS:
- /// This Singleton implementaion is limited to MonoBehaviors for Unity and does not prevent multiple
- /// instances of a class, only how many are able to be accessed through this class.
- ///
- /// USE:
- /// To access your singleton call the following:
- /// Singleton<ClassName>.Instance
- ///
- /// If no setup of your singleton is required ahead of time, this will be all you need, as the getter
- /// will create an instance. Otherwise, setup your object as required, then assign it as follows.
- ///
- /// To assign an instance as a singleton call the following when setting up your object (Start or Awake):
- /// Singleton<ClassName>.Instance = this;
- ///
- /// </summary>
- /// <typeparam name="T"></typeparam>
- public class Singleton<T> where T : MonoBehaviour {
- private static T instance;
- public static T Instance {
- //The getter will return the assigned instance, or create a new one has not been assigned.
- get {
- if (instance == null) {
- GameObject go = new GameObject();
- go.name = typeof(T).ToString() + "Singleton";
- instance = go.AddComponent<T>();
- }
- return instance;
- }
- //The setter will assign an instance as the singleton and destroy any pre-assigned instance.
- set {
- if (instance != null && instance != value) {
- GameObject.Destroy(instance);
- }
- instance = value;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement