using TMPro;
using UnityEngine;
public static class TMPInputSimulator
{
///
/// 模拟输入字符或字符串
///
public static void InsertText(CustomTMPInputField field, string textToInsert)
{
if (field == null) return;
int pos = field.caretPosition;
string currentText = field.text;
// 插入文字
field.text = currentText.Substring(0, pos) + textToInsert + currentText.Substring(pos);
field.caretPosition = pos + textToInsert.Length;
// 刷新显示
field.ForceLabelUpdate();
field.ForceRefresh();
// 触发 onValueChanged
field.onValueChanged?.Invoke(field.text);
}
///
/// 模拟删除光标前的字符(Backspace)
///
public static void Backspace(CustomTMPInputField field)
{
if (field == null) return;
int pos = field.caretPosition;
if (pos <= 0) return;
string currentText = field.text;
field.text = currentText.Substring(0, pos - 1) + currentText.Substring(pos);
field.caretPosition = pos - 1;
field.ForceLabelUpdate();
field.ForceRefresh();
field.onValueChanged?.Invoke(field.text);
}
///
/// 模拟删除光标后的字符(Delete)
///
public static void Delete(CustomTMPInputField field)
{
if (field == null) return;
int pos = field.caretPosition;
string currentText = field.text;
if (pos >= currentText.Length) return;
field.text = currentText.Substring(0, pos) + currentText.Substring(pos + 1);
field.caretPosition = pos;
field.ForceLabelUpdate();
field.ForceRefresh();
field.onValueChanged?.Invoke(field.text);
}
///
/// 移动光标到指定位置
///
public static void SetCaretPosition(CustomTMPInputField field, int position)
{
if (field == null) return;
field.caretPosition = Mathf.Clamp(position, 0, field.text.Length);
}
///
/// 移动光标到文本末尾
///
public static void MoveCaretToEnd(CustomTMPInputField field)
{
if (field == null) return;
field.caretPosition = field.text.Length;
}
}