Files
Gen_Hack-and-Slash-Roguelit…/Client/Assets/Scripts/Base/UIInputControl.cs

93 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using UI;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace Base
{
public class UIInputControl:Utils.MonoSingleton<UIInputControl>
{
public Dictionary<KeyCode, UIBase> UIwindowKeys = new();
private void Update()
{
foreach (var kvp in UIwindowKeys)
{
if (Input.GetKeyDown(kvp.Key))
{
HandleWindowActivation(kvp.Value);
break;
}
}
}
private void Init()
{
// 查找所有继承自 UIBase 的实例
UIBase[] uiInstances = Object.FindObjectsByType<UIBase>(FindObjectsSortMode.None);
foreach (var uiBase in uiInstances)
{
var key = uiBase.actionButton;
// 忽略 None 按键
if (key == KeyCode.None)
continue;
// 检查按键是否重复
if (UIwindowKeys.ContainsKey(key))
{
Debug.LogWarning($"Key '{key}' is already assigned to another window. Skipping...");
continue;
}
// 添加到字典
UIwindowKeys[key] = uiBase;
}
}
private void HandleWindowActivation(UIBase targetWindow)
{
// 遍历所有窗口,关闭非目标窗口
foreach (var kvp in UIwindowKeys)
{
if (kvp.Value != targetWindow && kvp.Value.IsVisible)
{
kvp.Value.Hide();
}
}
// 切换目标窗口的显示状态
if (targetWindow.IsVisible)
{
targetWindow.Hide(); // 如果已经打开,则关闭
}
else
{
targetWindow.Show(); // 如果未打开,则打开
}
}
private void OnDestroy()
{
// 移除事件监听
SceneManager.sceneLoaded -= OnSceneLoaded;
}
protected override void OnStart()
{
// 注册场景加载事件
SceneManager.sceneLoaded += OnSceneLoaded;
// 初始化时调用一次
Init();
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// 场景加载完成后调用 Init 方法
Init();
}
}
}