AlicizaX/Client/Assets/Scripts/CustomeModule/InputGlyph/InputGlyphText.cs

76 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using AlicizaX;
using UnityEngine;
using TMPro;
using UnityEngine.InputSystem;
[RequireComponent(typeof(TextMeshProUGUI))]
2026-03-09 20:38:15 +08:00
public sealed class InputGlyphText : MonoBehaviour
{
[SerializeField] private InputActionReference actionReference;
private TMP_Text textField;
2025-12-17 20:03:29 +08:00
private string _oldText;
2026-03-09 20:38:15 +08:00
private InputDeviceWatcher.InputDeviceCategory _cachedCategory;
private string _cachedFormattedText;
2026-03-11 13:04:31 +08:00
/// <summary>
/// 启用时初始化组件并订阅设备变更事件
/// </summary>
void OnEnable()
{
if (textField == null) textField = GetComponent<TMP_Text>();
InputDeviceWatcher.OnDeviceChanged += OnDeviceChanged;
2026-03-09 20:38:15 +08:00
_oldText = textField.text;
_cachedCategory = InputDeviceWatcher.InputDeviceCategory.Keyboard;
UpdatePrompt();
}
2026-03-11 13:04:31 +08:00
/// <summary>
/// 禁用时取消订阅设备变更事件
/// </summary>
void OnDisable()
{
InputDeviceWatcher.OnDeviceChanged -= OnDeviceChanged;
}
2026-03-11 13:04:31 +08:00
/// <summary>
/// 设备类型变更时的回调,更新文本显示
/// </summary>
void OnDeviceChanged(InputDeviceWatcher.InputDeviceCategory cat)
{
2026-03-09 20:38:15 +08:00
if (_cachedCategory != cat)
{
_cachedCategory = cat;
UpdatePrompt();
}
}
2026-03-11 13:04:31 +08:00
/// <summary>
/// 更新文本中的输入提示标签,使用 TextMeshPro 的 sprite 标签或文本回退
/// </summary>
void UpdatePrompt()
{
if (actionReference == null || actionReference.action == null || textField == null) return;
2026-03-09 20:38:15 +08:00
2026-03-11 13:04:31 +08:00
// 使用缓存的设备类型,避免重复查询 CurrentCategory
2026-03-09 20:38:15 +08:00
if (GlyphService.TryGetTMPTagForActionPath(actionReference, "", _cachedCategory, out string tag, out string displayFallback))
{
2026-03-09 20:38:15 +08:00
string formattedText = Utility.Text.Format(_oldText, tag);
if (_cachedFormattedText != formattedText)
{
_cachedFormattedText = formattedText;
textField.text = formattedText;
}
return;
}
2026-03-09 20:38:15 +08:00
string fallbackText = Utility.Text.Format(_oldText, displayFallback);
if (_cachedFormattedText != fallbackText)
{
_cachedFormattedText = fallbackText;
textField.text = fallbackText;
}
}
}