76 lines
2.3 KiB
C#
76 lines
2.3 KiB
C#
using System;
|
|
using System.Linq;
|
|
using AlicizaX;
|
|
using UnityEngine;
|
|
using TMPro;
|
|
using UnityEngine.InputSystem;
|
|
|
|
[RequireComponent(typeof(TextMeshProUGUI))]
|
|
public sealed class InputGlyphText : MonoBehaviour
|
|
{
|
|
[SerializeField] private InputActionReference actionReference;
|
|
private TMP_Text textField;
|
|
private string _oldText;
|
|
private InputDeviceWatcher.InputDeviceCategory _cachedCategory;
|
|
private string _cachedFormattedText;
|
|
|
|
/// <summary>
|
|
/// 启用时初始化组件并订阅设备变更事件
|
|
/// </summary>
|
|
void OnEnable()
|
|
{
|
|
if (textField == null) textField = GetComponent<TMP_Text>();
|
|
InputDeviceWatcher.OnDeviceChanged += OnDeviceChanged;
|
|
_oldText = textField.text;
|
|
_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>
|
|
/// 更新文本中的输入提示标签,使用 TextMeshPro 的 sprite 标签或文本回退
|
|
/// </summary>
|
|
void UpdatePrompt()
|
|
{
|
|
if (actionReference == null || actionReference.action == null || textField == null) return;
|
|
|
|
// 使用缓存的设备类型,避免重复查询 CurrentCategory
|
|
if (GlyphService.TryGetTMPTagForActionPath(actionReference, "", _cachedCategory, out string tag, out string displayFallback))
|
|
{
|
|
string formattedText = Utility.Text.Format(_oldText, tag);
|
|
if (_cachedFormattedText != formattedText)
|
|
{
|
|
_cachedFormattedText = formattedText;
|
|
textField.text = formattedText;
|
|
}
|
|
return;
|
|
}
|
|
|
|
string fallbackText = Utility.Text.Format(_oldText, displayFallback);
|
|
if (_cachedFormattedText != fallbackText)
|
|
{
|
|
_cachedFormattedText = fallbackText;
|
|
textField.text = fallbackText;
|
|
}
|
|
}
|
|
}
|