AlicizaX/Client/Assets/Scripts/CustomeModule/InputGlyph/InputGlyphImage.cs
2026-03-11 14:18:25 +08:00

73 lines
2.2 KiB
C#

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.InputSystem;
public sealed class InputGlyphImage : MonoBehaviour
{
[SerializeField] private InputActionReference actionReference;
[SerializeField] private Image targetImage;
[SerializeField] private bool hideIfMissing = false;
[SerializeField] private GameObject hideTargetObject;
private InputDeviceWatcher.InputDeviceCategory _cachedCategory;
private Sprite _cachedSprite;
/// <summary>
/// 启用时初始化组件并订阅设备变更事件
/// </summary>
void OnEnable()
{
if (targetImage == null) targetImage = GetComponent<Image>();
InputDeviceWatcher.OnDeviceChanged += OnDeviceChanged;
_cachedCategory = InputDeviceWatcher.InputDeviceCategory.Keyboard;
UpdatePrompt();
}
/// <summary>
/// 禁用时取消订阅设备变更事件
/// </summary>
void OnDisable()
{
InputDeviceWatcher.OnDeviceChanged -= OnDeviceChanged;
}
/// <summary>
/// 设备类型变更时的回调,更新图标显示
/// </summary>
void OnDeviceChanged(InputDeviceWatcher.InputDeviceCategory cat)
{
if (_cachedCategory != cat)
{
_cachedCategory = cat;
UpdatePrompt();
}
}
/// <summary>
/// 更新输入提示图标,并根据配置控制目标对象的显示/隐藏
/// </summary>
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;
}
}
if (hideTargetObject != null)
{
bool shouldBeActive = sprite != null && !hideIfMissing;
if (hideTargetObject.activeSelf != shouldBeActive)
{
hideTargetObject.SetActive(shouldBeActive);
}
}
}
}