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

89 lines
2.2 KiB
C#
Raw Normal View History

2026-03-20 13:11:41 +08:00
#if INPUTSYSTEM_SUPPORT
2026-03-19 19:50:32 +08:00
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
namespace UnityEngine.UI
{
[DisallowMultipleComponent]
public sealed class HotkeyComponent : MonoBehaviour, IHotkeyTrigger
{
[SerializeField] private Component _component;
[SerializeField] private InputActionReference _hotkeyAction;
2026-03-20 13:11:41 +08:00
[SerializeField] private EHotkeyPressType _hotkeyPressType = EHotkeyPressType.Performed;
2026-03-19 19:50:32 +08:00
public InputActionReference HotkeyAction
{
get => _hotkeyAction;
set => _hotkeyAction = value;
}
EHotkeyPressType IHotkeyTrigger.HotkeyPressType
{
get => _hotkeyPressType;
set => _hotkeyPressType = value;
}
2026-03-20 13:11:41 +08:00
private void Reset()
{
AutoAssignTarget();
}
private void OnEnable()
{
AutoAssignTarget();
((IHotkeyTrigger)this).BindHotKey();
}
private void OnDisable()
{
((IHotkeyTrigger)this).UnBindHotKey();
}
private void OnDestroy()
{
((IHotkeyTrigger)this).UnBindHotKey();
}
#if UNITY_EDITOR
private void OnValidate()
{
AutoAssignTarget();
}
#endif
2026-03-19 19:50:32 +08:00
void IHotkeyTrigger.HotkeyActionTrigger()
{
2026-03-20 13:11:41 +08:00
if (!isActiveAndEnabled || _component == null)
{
return;
}
if (_component is ISubmitHandler)
{
ExecuteEvents.Execute(
_component.gameObject,
new BaseEventData(EventSystem.current),
ExecuteEvents.submitHandler
);
return;
}
Debug.LogWarning($"{nameof(HotkeyComponent)} target must implement {nameof(ISubmitHandler)}: {_component.name}", this);
}
private void AutoAssignTarget()
{
if (_component != null)
{
return;
}
if (TryGetComponent(typeof(ISubmitHandler), out Component submitHandler))
2026-03-19 20:16:58 +08:00
{
2026-03-20 13:11:41 +08:00
_component = submitHandler;
2026-03-19 20:16:58 +08:00
}
2026-03-19 19:50:32 +08:00
}
}
}
2026-03-20 13:11:41 +08:00
#endif