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(); } } public partial class UIPresenter { [SerializeField] private UIRoot _root; [SerializeField] #if ODIN_INSPECTOR [Sirenix.OdinInspector.ReadOnly] #endif Dictionary _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() where T : IPage { this.GetPage(typeof(T).Name)?.Show(); } public void HidePage() where T : IPage { this.GetPage(typeof(T).Name)?.Hide(); } public bool IsInit { get; protected set; } Page GetPage() 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 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 GetAllPage() { var pages = this._root.Pages.GetComponentsInChildren(true); var canvasPages = this._root.CanvasPages.GetComponentsInChildren(true); var allPages = pages.AsEnumerable() .Concat(canvasPages.AsEnumerable()); return allPages; } private void InitMapper() { var pages = GetAllPage().ToArray(); _pageMapper = new Dictionary(); 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; } } }