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

80 lines
2.1 KiB
C#
Raw Normal View History

2025-10-13 20:20:01 +08:00
#if INPUTSYSTEM_SUPPORT
using System.Linq;
2025-09-25 11:09:09 +08:00
using AlicizaX.UI.Runtime;
using UnityEngine;
namespace UnityEngine.UI
2025-09-25 11:09:09 +08:00
{
public class HotkeyBindComponent : MonoBehaviour
{
private UIHolderObjectBase _holderObjectBase;
private void Awake()
{
_holderObjectBase = GetComponent<UIHolderObjectBase>();
2025-12-17 14:30:37 +08:00
_holderObjectBase.OnWindowBeforeShowEvent += BindHotKeys;
_holderObjectBase.OnWindowBeforeClosedEvent += UnBindHotKeys;
2025-09-25 11:09:09 +08:00
}
private void OnDestroy()
{
if (_holderObjectBase != null)
{
_holderObjectBase.OnWindowBeforeShowEvent -= BindHotKeys;
_holderObjectBase.OnWindowBeforeClosedEvent -= UnBindHotKeys;
}
2025-09-25 11:09:09 +08:00
}
2025-12-10 11:11:59 +08:00
[SerializeField] private Component[] hotButtons;
2025-09-25 11:09:09 +08:00
internal void BindHotKeys()
{
if (hotButtons == null) return;
2025-09-25 11:09:09 +08:00
for (int i = 0; i < hotButtons.Length; i++)
{
if (hotButtons[i] is IHotkeyTrigger trigger)
{
trigger.BindHotKey();
}
2025-09-25 11:09:09 +08:00
}
}
2025-12-10 11:11:59 +08:00
#if UNITY_EDITOR
[ContextMenu("Bind HotKeys")]
private void CollectUXHotkeys()
{
var found = gameObject
.GetComponentsInChildren<MonoBehaviour>(true)
.OfType<IHotkeyTrigger>()
2025-12-22 10:50:18 +08:00
.Where(t => t.HotkeyAction != null)
.Select(t => t as Component)
.ToArray();
hotButtons = found;
}
private void OnValidate()
{
if (_holderObjectBase == null)
{
_holderObjectBase = gameObject.GetComponent<UIHolderObjectBase>();
2025-12-22 10:17:53 +08:00
CollectUXHotkeys();
}
2025-12-10 11:11:59 +08:00
}
#endif
2025-09-25 11:09:09 +08:00
internal void UnBindHotKeys()
{
if (hotButtons == null) return;
2025-09-25 11:09:09 +08:00
for (int i = 0; i < hotButtons.Length; i++)
{
if (hotButtons[i] is IHotkeyTrigger trigger)
{
trigger.UnBindHotKey();
}
2025-09-25 11:09:09 +08:00
}
}
}
}
2025-10-13 20:20:01 +08:00
#endif