Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- /// <summary>
- /// This class is a singleton. Only one instance of this class can exist.
- /// </summary>
- public class SingletonMonoBehaviour<T> : DebugMonoBehaviour where T : Component
- {
- private static T instance;
- /// <summary>
- /// The singleton instance of this class.
- /// </summary>
- public static T Instance
- {
- get
- {
- if (instance == null)
- {
- instance = (T)FindObjectOfType(typeof(T));
- if (instance == null)
- {
- instance = CreateSingletonInstance<T>();
- }
- }
- return instance;
- }
- }
- /// <summary>
- /// Create a gameobject with itself attached.
- /// </summary>
- /// <returns>Return an instance of itself.</returns>
- private static T CreateSingletonInstance<T>() where T : Component
- {
- GameObject gameObject = new GameObject(typeof(T).GetType().Name);
- Debug.LogWarning("Could not find " + gameObject.name + ", creating", gameObject);
- return gameObject.AddComponent<T>();
- }
- /// <summary>
- /// Destroys the singleton. Important for cleaning up the static reference.
- /// </summary>
- public void OnDestroy()
- {
- instance = null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement