UIManager.cs
2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class UIManager : Singleton<UIManager>
{
/// <summary>
/// 缓存所有UI
/// </summary>
private Dictionary<string, UIBase> _dicUI = new Dictionary<string, UIBase>();
/// <summary>
/// 面板根节点
/// </summary>
public Transform uiRoot
{
get { return GameObject.Find("Top").transform; }
}
#region 管理UI
/// <summary>
/// 添加UI
/// </summary>
/// <param name="ui"></param>
public void RegisterUI(IUIBase ui)
{
var curUi = ui.GetUI();
if (!_dicUI.ContainsKey(curUi.GetType().Name))
{
_dicUI.Add(curUi.GetType().Name, curUi);
if (curUi.isCanDestroy)
{
curUi.transform.SetParent(uiRoot, false);
if (curUi.animationType == UIBase.EUiAnimationType.Fade)
{
curUi.GetOrAddComponent<CanvasGroup>().alpha = 0;
}
}
else
{
// 默认关闭所有UI
curUi.Close(this);
}
}
}
/// <summary>
/// 删除UI
/// </summary>
/// <param name="ui"></param>
public void UnRegisterUI(IUIBase ui)
{
var curUI = ui.GetUI();
if (_dicUI.ContainsKey(curUI.GetType().Name))
{
_dicUI.Remove(curUI.GetType().Name);
}
}
#endregion
#region 打开与关闭
private void ShowUI(string name)
{
if (!_dicUI.ContainsKey(name))
{
Debug.LogError("未找到对应的UI: " + name);
return;
}
_dicUI[name].Open(this);
}
private void HideUI(string name)
{
if (!_dicUI.ContainsKey(name))
{
Debug.LogError("未找到对应的UI: " + name);
return;
}
_dicUI[name].Close(this);
}
#endregion
/// <summary>
/// 打开
/// </summary>
public void ShowUI<T>()
{
ShowUI(typeof(T).Name);
}
/// <summary>
/// 关闭
/// </summary>
public void HideUI<T>()
{
HideUI(typeof(T).Name);
}
/// <summary>
/// 获得某个UI
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetUi<T>() where T : UIBase
{
var uiName = typeof(T).Name;
if (_dicUI.ContainsKey(uiName))
{
return _dicUI[uiName] as T;
}
Debug.LogError("未找到对应的UI: " + uiName);
return null;
}
}
public interface IUIBase
{
void RegisterUI() => UIManager.Instance.RegisterUI(this);
void UnRegisterUI() => UIManager.Instance.UnRegisterUI(this);
UIBase GetUI();
}