123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
-
- using UnityEngine;
- namespace NRKernal
- {
-
-
- public class SingleTon<T> where T : new()
- {
- private static T instane = default(T);
- public static void CreateInstance()
- {
- if(instane == null)
- {
- instane = new T();
- }
- }
-
-
- public static T Instance
- {
- get
- {
- if(instane == null)
- {
- CreateInstance();
- }
- return instane;
- }
- }
- }
-
-
- public class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T>
- {
-
- private static T instance;
-
-
-
-
-
- protected static T Instance
- {
- get
- {
- if (instance == null && searchForInstance)
- {
- searchForInstance = false;
- T[] objects = FindObjectsOfType<T>();
- if (objects.Length == 1)
- {
- instance = objects[0];
- }
- else if (objects.Length > 1)
- {
- Debug.LogErrorFormat("Expected exactly 1 {0} but found {1}.", typeof(T).ToString(), objects.Length);
- }
- }
- return instance;
- }
- }
-
- private static bool searchForInstance = true;
-
- public static void AssertIsInitialized()
- {
- Debug.Assert(IsInitialized, string.Format("The {0} singleton has not been initialized.", typeof(T).Name));
- }
-
-
- public static bool IsInitialized
- {
- get
- {
- return instance != null;
- }
- }
-
- protected bool isDirty = false;
-
-
-
-
- protected virtual void Awake()
- {
- if (IsInitialized && instance != this)
- {
- isDirty = true;
- DestroyImmediate(gameObject);
- NRDebugger.Info("Trying to instantiate a second instance of singleton class {0}. Additional Instance was destroyed", GetType().Name);
- }
- else if (!IsInitialized)
- {
- instance = (T)this;
- DontDestroyOnLoad(gameObject);
- }
- }
-
-
-
-
- protected virtual void OnDestroy()
- {
- if (instance == this)
- {
- instance = null;
- searchForInstance = true;
- }
- }
- }
- }
|