1
0
Fork 0
LaboratoryProtection/Assets/PMaker/UI/Scripts/UIPresenter.cs

145 lines
3.2 KiB
C#

using PMaker.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace PMaker.UI
{
//Unity API
public partial class UIPresenter : SingletonMonobehaviour
{
protected override void Awake()
{
base.Awake();
RuntimeInit();
}
private void Reset()
{
this._root = this.GetComponentInParent<UIRoot>();
}
}
public partial class UIPresenter
{
[SerializeField]
private UIRoot _root;
[SerializeField]
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.ReadOnly]
#endif
Dictionary<string, Page> _pageMapper;
}
// Public API
public partial class UIPresenter : IUIPresenter
{
public Page this[string pageName]
{
get
{
return this.GetPage(pageName);
}
set
{
this.SetPage(value);
}
}
public void ShowPage<T>() where T : IPage
{
this.GetPage(typeof(T).Name)?.Show();
}
public void HidePage<T>() where T : IPage
{
this.GetPage(typeof(T).Name)?.Hide();
}
public bool IsInit { get; protected set; }
Page GetPage<T>() where T : IPage
{
return this.GetPage(typeof(T).Name);
}
Page GetPage(string pageName)
{
if (_pageMapper.ContainsKey(pageName))
{
return _pageMapper[pageName];
}
else
{
Debug.Log($"{pageName}不存在");
return default;
}
}
void SetPage<T>(T page) where T : Page
{
var pageName = typeof(T).Name;
if (_pageMapper.ContainsKey(pageName))
{
Debug.Log($"{pageName}已存在");
}
else
{
_pageMapper[pageName] = page;
}
}
}
// Initializer
public partial class UIPresenter
{
#if ODIN_INSPECTOR
[Sirenix.OdinInspector.Button]
#endif
[ContextMenu("EditorInit")]
void EditorInit()
{
InitMapper();
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
private IEnumerable<Page> GetAllPage()
{
var pages = this._root.Pages.GetComponentsInChildren<Page>(true);
var canvasPages = this._root.CanvasPages.GetComponentsInChildren<Page>(true);
var allPages = pages.AsEnumerable()
.Concat(canvasPages.AsEnumerable());
return allPages;
}
private void InitMapper()
{
var pages = GetAllPage().ToArray();
_pageMapper = new Dictionary<string, Page>();
foreach (var item in pages)
{
_pageMapper[item.GetType().Name] = item;
}
}
private void RuntimeInit()
{
#if ODIN_INSPECTOR
if (this._pageMapper == null)
{
InitMapper();
}
#else
InitMapper();
#endif
this.IsInit = true;
}
}
}