Advertisement
Skjalgsm

SingletonMonoBehaviour

Feb 8th, 2012
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. /// <summary>
  4. /// This class is a singleton. Only one instance of this class can exist.
  5. /// </summary>
  6. public class SingletonMonoBehaviour<T> : DebugMonoBehaviour where T : Component
  7. {
  8.     private static T instance;
  9.  
  10.     /// <summary>
  11.     /// The singleton instance of this class.
  12.     /// </summary>
  13.     public static T Instance
  14.     {
  15.         get
  16.         {
  17.             if (instance == null)
  18.             {
  19.  
  20.                 instance = (T)FindObjectOfType(typeof(T));
  21.  
  22.                 if (instance == null)
  23.                 {
  24.                     instance = CreateSingletonInstance<T>();
  25.                 }
  26.             }
  27.  
  28.             return instance;
  29.         }
  30.     }
  31.  
  32.     /// <summary>
  33.     /// Create a gameobject with itself attached.
  34.     /// </summary>
  35.     /// <returns>Return an instance of itself.</returns>
  36.     private static T CreateSingletonInstance<T>() where T : Component
  37.     {
  38.         GameObject gameObject = new GameObject(typeof(T).GetType().Name);
  39.         Debug.LogWarning("Could not find " + gameObject.name + ", creating", gameObject);
  40.         return gameObject.AddComponent<T>();
  41.     }
  42.  
  43.     /// <summary>
  44.     /// Destroys the singleton. Important for cleaning up the static reference.
  45.     /// </summary>
  46.     public void OnDestroy()
  47.     {
  48.         instance = null;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement