2026-03-09 20:38:15 +08:00
|
|
|
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
|
2026-03-11 13:04:31 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 编辑器验证,自动获取 UXButton 组件
|
|
|
|
|
/// </summary>
|
2026-03-09 20:38:15 +08:00
|
|
|
private void OnValidate()
|
|
|
|
|
{
|
|
|
|
|
if (button == null)
|
|
|
|
|
{
|
|
|
|
|
button = GetComponent<UXButton>();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
#endif
|
|
|
|
|
|
2026-03-11 13:04:31 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 启用时初始化组件并订阅设备变更事件
|
|
|
|
|
/// </summary>
|
2026-03-09 20:38:15 +08:00
|
|
|
void OnEnable()
|
|
|
|
|
{
|
|
|
|
|
if (button == null) button = GetComponent<UXButton>();
|
|
|
|
|
if (targetImage == null) targetImage = GetComponent<Image>();
|
|
|
|
|
_actionReference = button.HotKeyRefrence;
|
|
|
|
|
InputDeviceWatcher.OnDeviceChanged += OnDeviceChanged;
|
|
|
|
|
_cachedCategory = InputDeviceWatcher.InputDeviceCategory.Keyboard;
|
|
|
|
|
UpdatePrompt();
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-11 13:04:31 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 禁用时取消订阅设备变更事件
|
|
|
|
|
/// </summary>
|
2026-03-09 20:38:15 +08:00
|
|
|
void OnDisable()
|
|
|
|
|
{
|
|
|
|
|
InputDeviceWatcher.OnDeviceChanged -= OnDeviceChanged;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-11 13:04:31 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 设备类型变更时的回调,更新图标显示
|
|
|
|
|
/// </summary>
|
2026-03-09 20:38:15 +08:00
|
|
|
void OnDeviceChanged(InputDeviceWatcher.InputDeviceCategory cat)
|
|
|
|
|
{
|
|
|
|
|
if (_cachedCategory != cat)
|
|
|
|
|
{
|
|
|
|
|
_cachedCategory = cat;
|
|
|
|
|
UpdatePrompt();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-11 13:04:31 +08:00
|
|
|
/// <summary>
|
|
|
|
|
/// 更新按钮的输入提示图标
|
|
|
|
|
/// </summary>
|
2026-03-09 20:38:15 +08:00
|
|
|
void UpdatePrompt()
|
|
|
|
|
{
|
|
|
|
|
if (_actionReference == null || _actionReference.action == null || targetImage == null) return;
|
|
|
|
|
|
2026-03-11 13:04:31 +08:00
|
|
|
// 使用缓存的设备类型,避免重复查询 CurrentCategory
|
2026-03-09 20:38:15 +08:00
|
|
|
if (GlyphService.TryGetUISpriteForActionPath(_actionReference, "", _cachedCategory, out Sprite sprite))
|
|
|
|
|
{
|
|
|
|
|
if (_cachedSprite != sprite)
|
|
|
|
|
{
|
|
|
|
|
_cachedSprite = sprite;
|
|
|
|
|
targetImage.sprite = sprite;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|