Advertisement
Guest User

GenericSingleton

a guest
Nov 25th, 2013
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.93 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GlobalManager<T> : MonoBehaviour {
  5.     [SerializeField]
  6.     bool _persistent = false;
  7.  
  8.     private static T _instance;
  9.     public static bool IsInstantianted { get { return _instance != null; } }
  10.     protected virtual void Init() {}
  11.  
  12.     public static T Instance {
  13.         get {
  14.             if (_instance != null)
  15.                 return _instance;
  16.             else {
  17.                 string errorMessage = typeof(T).Name + " is not attached to a GameObject or inactive.";
  18.                 Debug.LogError(errorMessage);
  19.                 throw new System.NullReferenceException(errorMessage);
  20.             }
  21.         }
  22.     }
  23.  
  24.     void Awake() {
  25.         if (Instantiation())
  26.             Init();
  27.     }
  28.  
  29.     bool Instantiation() {
  30.         if (IsInstantianted) {
  31.             Debug.LogWarning("Only one " + typeof(T) + " is allowed, destroying " + gameObject.name);
  32.             Destroy(gameObject);
  33.             return false;
  34.         }
  35.         _instance = (T) (object) this;
  36.  
  37.         if (_persistent)
  38.             DontDestroyOnLoad(this);
  39.         return true;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement