From b12511b825c64b8cb016e0ac9718a4d994bf9596 Mon Sep 17 00:00:00 2001 From: CortexCore <2630229280@qq.com> Date: Wed, 25 Dec 2024 11:35:30 +0800 Subject: [PATCH] 1 --- Src/Core/Utility/StopWatcher.cs | 6 +- Src/Core/Utility/ValidHandle.cs | 14 +++- Src/Unity/Scripts/Assets/BITFramework.cs | 76 ++++++++++--------- Src/Unity/Scripts/LoggerForUnity.cs | 33 ++++++-- Src/Unity/Scripts/UX/Alert/UXAlert.cs | 2 +- .../UX/Service/UI Toolkit/UIToolkitOverlay.cs | 9 +-- Src/Unity/Scripts/UX/Service/UXService.cs | 11 ++- Src/Unity/Scripts/UX/Waiting/UXWaiting.cs | 12 +-- 8 files changed, 100 insertions(+), 63 deletions(-) diff --git a/Src/Core/Utility/StopWatcher.cs b/Src/Core/Utility/StopWatcher.cs index 75b46c3..6a634e3 100644 --- a/Src/Core/Utility/StopWatcher.cs +++ b/Src/Core/Utility/StopWatcher.cs @@ -13,8 +13,12 @@ namespace BITKit { _logger = logger; _message = message; - _logger.LogInformation($"开始计时:{message}"); + + _logger.LogInformation($"开始计时:{message}"); + + _stopwatch.Start(); } + public void Dispose() { _stopwatch.Stop(); diff --git a/Src/Core/Utility/ValidHandle.cs b/Src/Core/Utility/ValidHandle.cs index 0369e8a..6703cb8 100644 --- a/Src/Core/Utility/ValidHandle.cs +++ b/Src/Core/Utility/ValidHandle.cs @@ -21,7 +21,7 @@ namespace BITKit } [CustomType(typeof(IValidHandle))] - public sealed class ValidHandle: IValidHandle + public sealed class ValidHandle: IValidHandle,IDisposable { public class MyHandle:IDisposable { @@ -71,7 +71,7 @@ namespace BITKit } public static implicit operator bool(ValidHandle validHandle) { - return validHandle.enableHandle; + return !validHandle._isDisposed && validHandle.enableHandle; } public bool Allow => this; @@ -88,7 +88,7 @@ namespace BITKit private bool tempEnable; private Action EventOnEnableChanged; private readonly Queue _completionSources = new(); - + private bool _isDisposed; public void AddElement(object obj) { @@ -224,6 +224,14 @@ namespace BITKit disableObjs.Clear(); Invoke(); } + + public void Dispose() + { + _isDisposed = true; + objs.Clear(); + disableObjs.Clear(); + EventOnEnableChanged = null; + } } } diff --git a/Src/Unity/Scripts/Assets/BITFramework.cs b/Src/Unity/Scripts/Assets/BITFramework.cs index 92316ae..c33ad3b 100644 --- a/Src/Unity/Scripts/Assets/BITFramework.cs +++ b/Src/Unity/Scripts/Assets/BITFramework.cs @@ -18,6 +18,7 @@ namespace BITKit { public class BITFramework : MonoBehaviour { + public static BITFramework Singleton { get; private set; } private static System.Diagnostics.Stopwatch Stopwatch; [RuntimeInitializeOnLoadMethod] @@ -29,17 +30,6 @@ namespace BITKit SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate); #endif } - // [SerializeField] private AssetReference serviceReference; - // private async void Start() - // { - // if(InitializationState is not InitializationState.None)return; - // InitializationState = InitializationState.Initializing; - // var asyncOperationHandle = serviceReference.LoadAssetAsync(); - // await UniTask.WaitUntil(() => asyncOperationHandle.IsDone); - // DontDestroyOnLoad(Instantiate(asyncOperationHandle.Result)); - // Stopwatch.Stop(); - // BIT4Log.Log($"BITFramework加载完成,耗时:{Stopwatch.ElapsedMilliseconds}ms"); - // } [SerializeReference, SubclassSelector] private IReference addressableName; [SerializeReference, SubclassSelector] private IReference packageName = new Reference("DefaultPackage"); @@ -69,6 +59,7 @@ namespace BITKit private Action _setProgressLabel; private async void Start() { + Singleton = this; try { #if UNITY_EDITOR @@ -151,10 +142,18 @@ namespace BITKit } } #endif - if (isOffline) + #if UNITY_5_3_OR_NEWER + if (IsEditorSimulateMode is false && isOffline) { initParameters = new OfflinePlayModeParameters(); } + #else + if (isOffline) + { + initParameters = new OfflinePlayModeParameters(); + } + #endif + InitializationOperation initOperation = null; try @@ -312,30 +311,7 @@ namespace BITKit YooAssetUtils.RegisterPackage(packageName.Value); YooAssetUtils.RegisterResourcePackage(package); - if (loadEntryScene.Allow) - { - _progressLabel.text="正在加载场景..."; - try - { - await package.LoadSceneAsync(loadEntryScene.Value); - _progressLabel.text="场景加载完成..."; - } - catch (Exception e) - { - Debug.LogException(e); - await UniTask.NextFrame(); - _progressLabel.text = e.Message; - } - } - else - { - _progressLabel.text="未找到默认场景,正在加载场景[1]"; - - SceneManager.LoadScene(1); - } - - if (document) - Destroy(document); + await AfterInit(package); } catch (Exception e) { @@ -343,9 +319,35 @@ namespace BITKit _progressBar.value =0; _progressLabel.text = e.Message; } - } + private async UniTask AfterInit(ResourcePackage package) + { + if (loadEntryScene.Allow) + { + _progressLabel.text="正在加载场景..."; + try + { + await package.LoadSceneAsync(loadEntryScene.Value); + _progressLabel.text="场景加载完成..."; + } + catch (Exception e) + { + Debug.LogException(e); + await UniTask.NextFrame(); + _progressLabel.text = e.Message; + } + } + else + { + _progressLabel.text="未找到默认场景,正在加载场景[1]"; + + SceneManager.LoadScene(1); + } + + if (document) + Destroy(document); + } private void OnDestroy() { #if UNITY_EDITOR diff --git a/Src/Unity/Scripts/LoggerForUnity.cs b/Src/Unity/Scripts/LoggerForUnity.cs index b7b9491..0901e9d 100644 --- a/Src/Unity/Scripts/LoggerForUnity.cs +++ b/Src/Unity/Scripts/LoggerForUnity.cs @@ -7,8 +7,9 @@ using ILogger = Microsoft.Extensions.Logging.ILogger; namespace BITKit { - public sealed class UnityLogger:ILogger + public abstract class UnityLogger:ILogger { + [HideInCallstack] public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { switch (logLevel) @@ -37,15 +38,37 @@ namespace BITKit return null; } } - public sealed class UnityLoggerProvider:ILoggerProvider + public sealed class UnityLogger:ILogger { - public void Dispose() + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { + switch (logLevel) + { + case LogLevel.Critical: + case LogLevel.Error: + if (exception is not null) + { + Debug.LogException(exception); + } + else + { + Debug.LogError($"{typeof(T).Name}:{state.ToString()}"); + } + break; + default: + Debug.Log($"{typeof(T).Name}:{state.ToString()}"); + break; + } } - public ILogger CreateLogger(string categoryName) + public bool IsEnabled(LogLevel logLevel) { - return new UnityLogger(); + return true; + } + + public IDisposable BeginScope(TState state) where TState : notnull + { + return null; } } } diff --git a/Src/Unity/Scripts/UX/Alert/UXAlert.cs b/Src/Unity/Scripts/UX/Alert/UXAlert.cs index 81dfc2e..7e60204 100644 --- a/Src/Unity/Scripts/UX/Alert/UXAlert.cs +++ b/Src/Unity/Scripts/UX/Alert/UXAlert.cs @@ -159,7 +159,7 @@ namespace BITKit.UX Dispose(); BITAppForUnity.AllowCursor.RemoveElement(this); } - public void Show(string content, string title = "Alert", Action confirmAction = null, Action onChoose = null) + public async void Show(string content, string title = "Alert", Action confirmAction = null, Action onChoose = null) { PrintAlertMessage(new AlertMessage() { diff --git a/Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitOverlay.cs b/Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitOverlay.cs index 390387b..48f1ce8 100644 --- a/Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitOverlay.cs +++ b/Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitOverlay.cs @@ -12,19 +12,18 @@ namespace BITKit.UX protected readonly CancellationTokenSource CancellationToken; protected readonly IUXService UXService; protected VisualElement RootVisualElement { get; set; } - private bool _initialized; + protected bool IsInitialized { get; private set; } protected UIToolkitOverlay(IUXService uxService, CancellationTokenSource cancellationToken) { UXService = uxService; CancellationToken = cancellationToken; CancellationToken.Token.Register(Dispose); } - protected abstract string DocumentPath { get; } // ReSharper disable once MemberCanBeProtected.Global public virtual async UniTask InitializeAsync() { - if(_initialized)return; + if(IsInitialized)return; var asset =await ModService.LoadAsset(DocumentPath); var root= RootVisualElement = UXService.Root.As().Create(asset); @@ -40,12 +39,12 @@ namespace BITKit.UX root.style.right = 0; UXUtils.Inject(this); - _initialized = true; + IsInitialized = true; } public virtual void Dispose() { if(RootVisualElement is null)return; - _initialized = false; + IsInitialized = false; RootVisualElement.RemoveFromHierarchy(); RootVisualElement = null; } diff --git a/Src/Unity/Scripts/UX/Service/UXService.cs b/Src/Unity/Scripts/UX/Service/UXService.cs index 31ec342..b7fdb19 100644 --- a/Src/Unity/Scripts/UX/Service/UXService.cs +++ b/Src/Unity/Scripts/UX/Service/UXService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Text; +using System.Threading; using BITKit.Mod; using Cysharp.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; @@ -17,10 +18,12 @@ namespace BITKit.UX { private readonly IAfterTicker _ticker; private readonly IServiceProvider _serviceProvider; - public UXService(IAfterTicker ticker, IServiceProvider serviceProvider) + private readonly CancellationTokenSource _cancellationTokenSource; + public UXService(IAfterTicker ticker, IServiceProvider serviceProvider, CancellationTokenSource cancellationTokenSource) { _ticker = ticker; _serviceProvider = serviceProvider; + _cancellationTokenSource = cancellationTokenSource; _entryGroup.OnEntry += OnEntry; _ticker.Add(OnTick); } @@ -74,6 +77,12 @@ namespace BITKit.UX var gameObject = new GameObject("UXService"); Object.DontDestroyOnLoad(gameObject); + + _cancellationTokenSource.Token.Register(() => + { +Object.Destroy(gameObject); + }); + var document = gameObject.AddComponent(); try { diff --git a/Src/Unity/Scripts/UX/Waiting/UXWaiting.cs b/Src/Unity/Scripts/UX/Waiting/UXWaiting.cs index f7bc381..621afd9 100644 --- a/Src/Unity/Scripts/UX/Waiting/UXWaiting.cs +++ b/Src/Unity/Scripts/UX/Waiting/UXWaiting.cs @@ -83,17 +83,9 @@ namespace BITKit { handle.Dispose(); } - private async void OnTick(float deltaTime) + private void OnTick(float deltaTime) { - switch (_initializationState) - { - case InitializationState.None: - _initializationState = InitializationState.Initializing; - await InitializeAsync(); - break; - case InitializationState.Initializing: - return; - } + if(_initializationState is not InitializationState.Initialized)return; while (_initializedHandles.TryDequeue(out var handle)) { var container = _container.Create(_handleTemplate);