This commit is contained in:
CortexCore 2024-12-25 11:35:30 +08:00
parent 5b7ac3c361
commit b12511b825
8 changed files with 100 additions and 63 deletions

View File

@ -13,8 +13,12 @@ namespace BITKit
{
_logger = logger;
_message = message;
_logger.LogInformation($"开始计时:{message}");
_stopwatch.Start();
}
public void Dispose()
{
_stopwatch.Stop();

View File

@ -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<bool> EventOnEnableChanged;
private readonly Queue<UniTaskCompletionSource> _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;
}
}
}

View File

@ -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<GameObject>();
// await UniTask.WaitUntil(() => asyncOperationHandle.IsDone);
// DontDestroyOnLoad(Instantiate(asyncOperationHandle.Result));
// Stopwatch.Stop();
// BIT4Log.Log<BITFramework>($"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<string> _setProgressLabel;
private async void Start()
{
Singleton = this;
try
{
#if UNITY_EDITOR
@ -151,10 +142,18 @@ namespace BITKit
}
}
#endif
#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,6 +311,18 @@ namespace BITKit
YooAssetUtils.RegisterPackage(packageName.Value);
YooAssetUtils.RegisterResourcePackage(package);
await AfterInit(package);
}
catch (Exception e)
{
await UniTask.SwitchToMainThread();
_progressBar.value =0;
_progressLabel.text = e.Message;
}
}
private async UniTask AfterInit(ResourcePackage package)
{
if (loadEntryScene.Allow)
{
_progressLabel.text="正在加载场景...";
@ -337,15 +348,6 @@ namespace BITKit
if (document)
Destroy(document);
}
catch (Exception e)
{
await UniTask.SwitchToMainThread();
_progressBar.value =0;
_progressLabel.text = e.Message;
}
}
private void OnDestroy()
{
#if UNITY_EDITOR

View File

@ -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<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
switch (logLevel)
@ -37,15 +38,37 @@ namespace BITKit
return null;
}
}
public sealed class UnityLoggerProvider:ILoggerProvider
public sealed class UnityLogger<T>:ILogger<T>
{
public void Dispose()
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> 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>(TState state) where TState : notnull
{
return null;
}
}
}

View File

@ -159,7 +159,7 @@ namespace BITKit.UX
Dispose();
BITAppForUnity.AllowCursor.RemoveElement(this);
}
public void Show(string content, string title = "Alert", Action confirmAction = null, Action<bool> onChoose = null)
public async void Show(string content, string title = "Alert", Action confirmAction = null, Action<bool> onChoose = null)
{
PrintAlertMessage(new AlertMessage()
{

View File

@ -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<VisualTreeAsset>(DocumentPath);
var root= RootVisualElement = UXService.Root.As<VisualElement>().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;
}

View File

@ -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<UIDocument>();
try
{

View File

@ -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);