81 lines
2.2 KiB
C#
81 lines
2.2 KiB
C#
#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
|