com.alicizax.unity.ui.exten.../Runtime/UXComponent/Hotkey/HotkeyBindComponent.cs

84 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#if INPUTSYSTEM_SUPPORT
using System.Linq;
using AlicizaX.UI.Runtime;
using UnityEngine;
namespace UnityEngine.UI
{
public class HotkeyBindComponent : MonoBehaviour
{
private UIHolderObjectBase _holderObjectBase;
private void Awake()
{
_holderObjectBase = GetComponent<UIHolderObjectBase>();
_holderObjectBase.OnWindowBeforeShowEvent += BindHotKeys;
_holderObjectBase.OnWindowBeforeClosedEvent += UnBindHotKeys;
}
private void OnDestroy()
{
if (_holderObjectBase != null)
{
_holderObjectBase.OnWindowBeforeShowEvent -= BindHotKeys;
_holderObjectBase.OnWindowBeforeClosedEvent -= UnBindHotKeys;
}
}
// 改成 Component[](或 MonoBehaviour[]Unity 可以序列化 Component 引用
[SerializeField] private Component[] hotButtons;
internal void BindHotKeys()
{
if (hotButtons == null) return;
for (int i = 0; i < hotButtons.Length; i++)
{
if (hotButtons[i] is IHotkeyTrigger trigger)
{
trigger.BindHotKey();
}
}
}
#if UNITY_EDITOR
[ContextMenu("Bind HotKeys")]
private void CollectUXHotkeys()
{
// 更稳健的查找:先拿所有 MonoBehaviour再 OfType 接口
var found = gameObject
.GetComponentsInChildren<MonoBehaviour>(true)
.OfType<IHotkeyTrigger>()
.Where(t => t.HotkeyAction != null) // 保留原来的筛选条件(如果 HotkeyAction 存在)
.Select(t => t as Component)
.ToArray();
hotButtons = found;
Debug.Log($"[HotkeyBindComponent] 已找到 {hotButtons.Length} 个 UXHotkey 组件并绑定。");
}
private void OnValidate()
{
if (_holderObjectBase == null)
{
_holderObjectBase = gameObject.GetComponent<UIHolderObjectBase>();
CollectUXHotkeys();
}
}
#endif
internal void UnBindHotKeys()
{
if (hotButtons == null) return;
for (int i = 0; i < hotButtons.Length; i++)
{
if (hotButtons[i] is IHotkeyTrigger trigger)
{
trigger.UnBindHotKey();
}
}
}
}
}
#endif