123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
-
- 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
- {
- return instance;
- }
- }
-
-
-
- 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;
- }
- }
- }
|