using System; using System.Collections.Generic; using System.Linq; using Code.Infrastructure.Configs; using Code.Infrastructure.EventBus; using Cysharp.Threading.Tasks; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; namespace Code.Infrastructure.UI { public interface IUIFactory { UniTaskVoid LoadPanel(UIPanelType panelType); void ReleasePanel(UIPanel panel); } public class UIFactory : IDisposable, IUIFactory { private Dictionary _configs; private string _configsLabel; private EventBus.EventBus _eventBus; private AsyncOperationHandle> _configsHandle; public UIFactory(IConfigLocator configLocator, EventBus.EventBus eventBus) { _eventBus = eventBus; _configsLabel = configLocator.TryGetManyConfigAssetReferences(); LoadConfigs().Forget(); } public async UniTaskVoid LoadPanel(UIPanelType panelType) { var panel = (await Addressables.InstantiateAsync(_configs[panelType]).ToUniTask()).GetComponent(); _eventBus.RaiseEvent(ui => ui.UIPanelLoaded(panel, panelType)); } public void ReleasePanel(UIPanel panel) { Addressables.ReleaseInstance(panel.gameObject); } private async UniTaskVoid LoadConfigs() { _configsHandle = Addressables.LoadAssetsAsync(_configsLabel); await _configsHandle.ToUniTask(); _configs = _configsHandle.Result.ToDictionary(c => c.UIPanelType); _eventBus.RaiseEvent(ui => ui.UIInitialized()); } public void Dispose() { Addressables.Release(_configsHandle); } } public interface IUIInitializedHandle : IGlobalSubscriber { void UIInitialized(); } public interface IUIPanelLoadedHandle : IGlobalSubscriber { void UIPanelLoaded(UIPanel panel, UIPanelType panelType); } }