forked from zxl/Frame
1
0
Fork 0
Frame/Assets/Scripts/UI/UIManager.cs

150 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using UnityEngine;
namespace Game
{
public class UIManager : ManagerBase, IUIManager
{
private static UIManager instance;
public static UIManager Instance
{
get
{
if (instance == null)
{
instance = new UIManager();
}
return instance;
}
}
private Queue<UIBase> _uis = new Queue<UIBase>();
private Dictionary<UIType, UIBase> _uiDic = new Dictionary<UIType, UIBase>();
private Dictionary<UIType, Type> _types = new Dictionary<UIType, Type>();
protected override void OnInit()
{
base.OnInit();
foreach (var type in this.GetType().Assembly.GetTypes())
{
if (!typeof(UIBase).IsAssignableFrom(type))
continue;
var uiTypeAttribute = type.GetCustomAttribute<UITypeAttribute>();
if(uiTypeAttribute==null)
continue;
_types.Add(uiTypeAttribute.UIType, type);
}
}
protected override void OnUpdate(float dateTime)
{
base.OnUpdate(dateTime);
foreach (var ui in _uis)
{
ui.Update(dateTime);
}
}
protected override void OnPause()
{
base.OnPause();
foreach (var ui in _uis)
{
ui.Pause();
}
}
protected override void OnResume()
{
base.OnResume();
foreach (var ui in _uis)
{
ui.Resume();
}
}
public IUI CreateUI(UIType uiType)
{
var gameObject = ResourceManager.Instance.LoadUIGameObjectSync(uiType.ToString());
if (!this._types.TryGetValue(uiType,out var type))
{
throw new InvalidOperationException();
}
if (Activator.CreateInstance(type,false) is not UIBase ui)
throw new NullReferenceException();
ui.SetGameObject(gameObject);
#if UNITY_EDITOR
gameObject.AddComponent<UIInfo>().ui = ui;
#endif
ui.Init();
_uiDic.Add(uiType, ui);
return ui;
}
public IUI ShowUI(UIType uiType)
{
if (_uiDic.TryGetValue(uiType, out var ui))
{
_uis.Enqueue(ui);
ui.Open();
return ui;
}
return null;
}
public T GetUI<T>(UIType uiType) where T : UIBase
{
if (_uiDic.TryGetValue(uiType, out var ui))
{
if (ui is not T t)
throw new InvalidCastException();
return t;
}
return default;
}
public bool HideUI(UIType uiType)
{
if (_uiDic.TryGetValue(uiType, out var ui))
{
ui.Close();
return true;
}
return false;
}
public IUI CloseLast()
{
if (_uis.Count > 0)
{
var ui = _uis.Dequeue();
ui.Close();
return ui;
}
return null;
}
public void CloseAll()
{
while (_uis.Count > 0)
{
var ui = _uis.Dequeue();
ui.Close();
}
}
}
}