Files
Infratest/Assets/Code/Infrastructure/UI/UIService.cs
T

88 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using Code.Infrastructure.EventBus;
using Reflex.Core;
using Reflex.Extensions;
using Reflex.Injectors;
using UnityEngine.SceneManagement;
namespace Code.Infrastructure.UI
{
public interface IUIService
{
void OpenPanel(UIPanelType uiPanelType);
void ClosePanel(UIPanelType uiPanelType);
void TryLoadPanel(UIPanelType uiPanelType);
void TryRemovePanel(UIPanelType uiPanelType);
void SetCanvasCamera(UnityEngine.Camera camera);
UIPanel TryGetPanel(UIPanelType panelType);
}
public class UIService : IUIPanelLoadedHandle, IUIService
{
private Dictionary<UIPanelType, UIPanel> _loadedPanels = new();
private EventBus.EventBus _eventBus;
private IUIFactory _factory;
public UIService(EventBus.EventBus eventBus, IUIFactory factory)
{
_eventBus = eventBus;
_factory = factory;
eventBus.Subscribe(this);
}
public void SetCanvasCamera(UnityEngine.Camera camera)
{
_factory.Canvas.worldCamera = camera;
_factory.Canvas.planeDistance = 0.3f;
}
public void OpenPanel(UIPanelType uiPanelType)
{
_loadedPanels[uiPanelType].gameObject.SetActive(true);
_loadedPanels[uiPanelType].Open();
}
// TODO Close event
public void ClosePanel(UIPanelType uiPanelType)
{
_loadedPanels[uiPanelType].Close(() => { _loadedPanels[uiPanelType].gameObject.SetActive(false); });
}
public void TryLoadPanel(UIPanelType uiPanelType) => _factory.LoadPanel(uiPanelType);
public void UIPanelLoaded(UIPanel panel, UIPanelType panelType)
{
_loadedPanels.Add(panelType, panel);
if (panel.InjectMeSenpai)
GameObjectInjector.InjectRecursive(panel.gameObject, Container.RootContainer);
// GameObjectInjector.InjectRecursive(panel.gameObject, SceneManager.GetActiveScene().GetSceneContainer()); // Скорее всего будут нужны компоненты текущей сцены
_eventBus.RaiseEvent<IUIPanelLoaded>(ui => ui.UILoaded(panelType));
}
public void TryRemovePanel(UIPanelType uiPanelType)
{
_loadedPanels[uiPanelType].Close(() =>
{
_loadedPanels[uiPanelType].gameObject.SetActive(false);
RemovePanel(uiPanelType);
});
}
private void RemovePanel(UIPanelType panelType)
{
_factory.ReleasePanel(_loadedPanels[panelType]);
_loadedPanels.Remove(panelType);
}
public UIPanel TryGetPanel(UIPanelType panelType) => _loadedPanels.GetValueOrDefault(panelType);
}
public interface IUIPanelLoaded : IGlobalSubscriber
{
void UILoaded(UIPanelType uiPanelType);
}
}