AlicizaX/Client/Assets/InputGlyph/InputGlyphUXButton.cs
2026-03-09 20:38:15 +08:00

64 lines
1.7 KiB
C#

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
private void OnValidate()
{
if (button == null)
{
button = GetComponent<UXButton>();
}
}
#endif
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();
}
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;
// Use cached category instead of re-querying CurrentCategory
if (GlyphService.TryGetUISpriteForActionPath(_actionReference, "", _cachedCategory, out Sprite sprite))
{
if (_cachedSprite != sprite)
{
_cachedSprite = sprite;
targetImage.sprite = sprite;
}
}
}
}