需求:为了方便UI的管理,编写一个管理类,管理所有UI的加载、隐藏或销魂,每个UI都继承自一个UIWindow类,存放在Resource的指定目录下,通过UIManager进行管理。每个继承自UIWindow的UI天然有UI的打开关闭等基本功能。
UIWindow
using UnityEngine;public abstract class UIWindow : MonoBehaviour
{public delegate void CloseHandler(UIWindow sender, WindowResult result);public event CloseHandler OnClose;public UIWindowType WindowType= UIWindowType.Page;public virtual System.Type Type { get { return this.GetType(); } }public GameObject Root;public enum WindowResult{None = 0,Yes,No,}public void Close(WindowResult result = WindowResult.None){UIManager.Instance.Close(this.Type);if (this.OnClose != null)this.OnClose(this, result);this.OnClose = null;}public virtual void OnCloseClick(){this.Close();}public virtual void OnYesClick(){this.Close(WindowResult.Yes);}public virtual void OnNoClick(){this.Close(WindowResult.No);}
}
UIManager
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;public class UIManager : Singleton<UIManager>
{class UIElement{public string Resources;public bool Cache ;public GameObject Instance;}private Dictionary<Type, UIElement> UIResources = new();private Transform UIParent;public void Init( Transform parent = null){UIParent = parent;//UI在这注册UIResources.Add(typeof(UIHomePage), new UIElement() { Resources = "Prefabs/UI/HomePage/UIHomePage", Cache= true });}public T Show<T>() where T : class{Type type = typeof(T);if (UIResources.ContainsKey(type)){UIElement info = UIResources[type];if (info.Instance != null){info.Instance.SetActive(true);}else{if (Resources.Load(info.Resources) == null){return default;}info.Instance = GameObject.Instantiate(ResourcesManager.Instance.LoadAsset<GameObject>(info.Resources));}return info.Instance.GetComponent<T>();}return default;}public void Close(Type type){if (UIResources.ContainsKey(type)){UIElement info = UIResources[type];if (info.Cache){info.Instance.SetActive(false);}else{GameObject.Destroy(info.Instance);info.Instance = null;}}}public void Close<T>(){Close(typeof(T));}public void CloseIfShow<T>(){Type type = typeof(T);if(UIResources.ContainsKey(type)&& UIResources[type].Instance && UIResources[type].Instance.activeSelf == true){Close(typeof(T));}}}
使用
如果要给组件挂上UIHomePage脚本,则给它继承一下UIWindow
public class AddressPageUI : UIWindow
{
}
然后在上面的UIManager注册函数即可,
UIResources.Add(typeof(UIHomePage), new UIElement() { Resources = "Prefabs/UI/HomePage/UIHomePage", Cache= true });
加载时
UIManager .Instance.Show<AddressPageUI >();
关闭时
UIManager .Instance.Close<AddressPageUI>();
如果UI上有关闭确定等按钮,直接管理基类中的函数即可,无需另外编写函数