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; /// /// 启用时初始化组件并订阅设备变更事件 /// void OnEnable() { if (targetImage == null) targetImage = GetComponent(); 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; } } if (hideTargetObject != null) { bool shouldBeActive = sprite != null && !hideIfMissing; if (hideTargetObject.activeSelf != shouldBeActive) { hideTargetObject.SetActive(shouldBeActive); } } } }