using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;
[RequireComponent(typeof(UXButton))]
public sealed class InputGlyphUXButton : MonoBehaviour
{
[SerializeField] private UXButton button;
[SerializeField] private Image targetImage;
private InputActionReference _actionReference;
private InputDeviceWatcher.InputDeviceCategory _cachedCategory;
private Sprite _cachedSprite;
#if UNITY_EDITOR
///
/// 编辑器验证,自动获取 UXButton 组件
///
private void OnValidate()
{
if (button == null)
{
button = GetComponent();
}
}
#endif
///
/// 启用时初始化组件并订阅设备变更事件
///
void OnEnable()
{
if (button == null) button = GetComponent();
if (targetImage == null) targetImage = GetComponent();
_actionReference = button.HotKeyRefrence;
InputDeviceWatcher.OnDeviceChanged += OnDeviceChanged;
_cachedCategory = InputDeviceWatcher.InputDeviceCategory.Keyboard;
UpdatePrompt();
}
///
/// 禁用时取消订阅设备变更事件
///
void OnDisable()
{
InputDeviceWatcher.OnDeviceChanged -= OnDeviceChanged;
}
///
/// 设备类型变更时的回调,更新图标显示
///
void OnDeviceChanged(InputDeviceWatcher.InputDeviceCategory cat)
{
if (_cachedCategory != cat)
{
_cachedCategory = cat;
UpdatePrompt();
}
}
///
/// 更新按钮的输入提示图标
///
void UpdatePrompt()
{
if (_actionReference == null || _actionReference.action == null || targetImage == null) return;
// 使用缓存的设备类型,避免重复查询 CurrentCategory
if (GlyphService.TryGetUISpriteForActionPath(_actionReference, "", _cachedCategory, out Sprite sprite))
{
if (_cachedSprite != sprite)
{
_cachedSprite = sprite;
targetImage.sprite = sprite;
}
}
}
}