|
- using System;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class UIManager : MonoBehaviour
- {
- public static UIManager Instance { get; private set; }
-
- private Dictionary<string, UIBase> uiDict = new Dictionary<string, UIBase>();
-
- // Èý¸ö²ã¼¶½Úµã£ºLow, Mid, High
- public Transform lowLayer;
- public Transform midLayer;
- public Transform highLayer;
-
- private void Awake()
- {
- Instance = this;
- }
-
- public T OpenUI<T>(object param = null, int layer = 1) where T : UIBase
- {
- string uiName = typeof(T).Name;
-
- if (uiDict.TryGetValue(uiName, out var ui))
- {
- ui.gameObject.SetActive(true);
- ui.OnOpen(param);
- return ui as T;
- }
-
- GameObject prefab = Resources.Load<GameObject>($"UI/{uiName}");
- if (prefab == null)
- {
- Debug.LogError($"UI Prefab not found: {uiName}");
- return null;
- }
-
- Transform parent = GetLayerParent(layer);
- GameObject go = Instantiate(prefab, parent);
- T uiInstance = go.GetComponent<T>();
- if (uiInstance == null)
- {
- Debug.LogError($"UI Prefab does not have component: {uiName}");
- return null;
- }
-
- uiDict[uiName] = uiInstance;
- uiInstance.OnOpen(param);
- return uiInstance;
- }
-
- public void CloseUI(string uiName)
- {
- if (uiDict.TryGetValue(uiName, out var ui))
- {
- ui.OnClose();
- Destroy(ui.gameObject);
- uiDict.Remove(uiName);
- }
- }
-
- public void CloseAll()
- {
- foreach (var kv in uiDict)
- {
- kv.Value.OnClose();
- Destroy(kv.Value.gameObject);
- }
- uiDict.Clear();
- }
-
- private Transform GetLayerParent(int layer)
- {
- return layer switch
- {
- 0 => lowLayer,
- 1 => midLayer,
- 2 => highLayer,
- _ => midLayer,
- };
- }
- }
|