AlicizaX/Client/Assets/InputGlyph/ActionPromptTMP.cs
2025-12-05 20:57:29 +08:00

77 lines
2.4 KiB
C#

using InputGlyphsFramework;
using UnityEngine;
using TMPro;
using UnityEngine.InputSystem;
[RequireComponent(typeof(RectTransform))]
public class ActionPromptTMP : MonoBehaviour
{
public InputActionReference actionReference;
public TMP_Text textField;
public string template = "({0})";
string lastRendered;
void OnEnable()
{
if (textField == null) textField = GetComponentInChildren<TMP_Text>();
if (InputService.Instance != null) InputService.Instance.OnBindingChanged += OnBindingChanged;
InputDeviceWatcher.OnDeviceChanged += OnDeviceChanged;
UpdatePrompt();
}
void OnDisable()
{
if (InputService.Instance != null) InputService.Instance.OnBindingChanged -= OnBindingChanged;
InputDeviceWatcher.OnDeviceChanged -= OnDeviceChanged;
}
void OnBindingChanged(InputAction action, int idx)
{
if (actionReference == null || actionReference.action == null) return;
if (action == actionReference.action) UpdatePrompt();
}
void OnDeviceChanged(InputDeviceWatcher.InputDeviceCategory cat)
{
UpdatePrompt();
}
void UpdatePrompt()
{
if (actionReference == null || actionReference.action == null || textField == null) return;
var action = actionReference.action;
string path = InputService.GetBindingControlPath(action);
var device = InputDeviceWatcher.CurrentCategory;
string displayFallback = string.Empty;
if (GlyphService.Instance != null && GlyphService.Instance.TryGetTMPTagForActionPath(path, device, out string tag, out displayFallback))
{
var s = string.Format(template, tag);
if (s != lastRendered)
{
textField.text = s;
lastRendered = s;
}
return;
}
var display = InputService.GetBindingDisplay(action);
var fallback = string.Format(template, string.IsNullOrEmpty(display) ? (displayFallback ?? GetDisplayFromPath(path)) : display);
if (fallback != lastRendered)
{
textField.text = fallback;
lastRendered = fallback;
}
}
string GetDisplayFromPath(string path)
{
if (string.IsNullOrEmpty(path)) return string.Empty;
var parts = path.Split('/');
var last = parts[parts.Length - 1].Trim(new char[] { '{', '}', '<', '>', '\'', '"' });
return last;
}
}