com.alicizax.unity.ui.exten.../Runtime/UXComponent/Hotkey/HotkeyBindComponent.cs
2025-12-22 10:50:18 +08:00

81 lines
2.2 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()
{
var found = gameObject
.GetComponentsInChildren<MonoBehaviour>(true)
.OfType<IHotkeyTrigger>()
.Where(t => t.HotkeyAction != null)
.Select(t => t as Component)
.ToArray();
hotButtons = found;
}
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