Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- namespace TemporalRealms.Utility {
- /// <summary>
- /// Generic singleton base class for global, single-instance MonoBehaviors.
- /// </summary>
- /// <typeparam name="T">The class type to define</typeparam>
- public class SingletonMonoBehaviour<T> : MonoBehaviour where T : Component {
- /// <summary>
- /// Storage for the singleton instance.
- /// </summary>
- private static T instance;
- /// <summary>
- /// Property that either creates or returns the existing singleton instance.
- /// </summary>
- public static T Instance {
- get {
- if (instance != null) return instance;
- instance = FindObjectOfType<T>();
- if (instance != null) return instance;
- var obj = new GameObject { name = typeof(T).Name };
- instance = obj.AddComponent<T>();
- return instance;
- }
- }
- /// <summary>
- /// Makes sure that the instance doesn't get destroyed when switching screens.
- /// </summary>
- public virtual void Awake() {
- if (instance == null) {
- instance = this as T;
- DontDestroyOnLoad(gameObject);
- } else {
- Destroy(gameObject);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment