12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
-
- using System;
- using UnityEngine;
- namespace XRTool.Util
- {
-
-
-
-
-
-
- public abstract class UnitySingleton<T> : MonoBehaviour where T : UnitySingleton<T>
- {
- public static event Action InitComplte;
- public static event Action DeleteSingle;
- private static T instance;
- public static T Instance
- {
- get
- {
- try
- {
- return instance;
- }
- catch
- {
- return null;
- }
- }
- }
-
-
-
- public static bool IsInitialized
- {
- get
- {
- return instance != null;
- }
- }
-
-
-
-
- public static T ForceInstance()
- {
- if (!instance)
- {
- GameObject obj = new GameObject();
- instance= obj.AddComponent<T>();
- }
- return instance;
- }
-
-
-
- protected virtual void Awake()
- {
- if (instance != null && instance.gameObject != gameObject)
- {
- Debug.LogErrorFormat("{0}为单例对象,但是场景中存在多个{0},已删除本对象", GetType().Name);
- Destroy(gameObject);
- }
- else
- {
- DeleteSingle = null;
- instance = (T)this;
- InitComplte?.Invoke();
- }
- }
-
-
-
- protected virtual void OnDestroy()
- {
- if (instance == this)
- {
- instance = null;
- DeleteSingle?.Invoke();
- }
- InitComplte = null;
- }
- }
- }
|