72 lines
2.2 KiB
C#
72 lines
2.2 KiB
C#
|
|
using TMPro;
|
|||
|
|
using UnityEngine;
|
|||
|
|
using UnityEngine.UI;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 适配器:让 CustomKeyboard 可以直接操作 TMP_InputField
|
|||
|
|
/// 实现类似 InputDialog 的接口但实际修改 InputField
|
|||
|
|
/// </summary>
|
|||
|
|
public class KeyboardInputAdapter : MonoBehaviour
|
|||
|
|
{
|
|||
|
|
private TMP_InputField _inputField;
|
|||
|
|
private object _manager; // CustomKeyboardManager,使用 object 避免循环引用
|
|||
|
|
public Button ConfirmButton; // 虚拟确认按钮
|
|||
|
|
private bool _shouldClearOnFirstInput = false; // 是否在首次输入时清空
|
|||
|
|
private bool _hasInputOccurred = false; // 是否已经发生过输入
|
|||
|
|
|
|||
|
|
public void SetTarget(TMP_InputField inputField, object manager, bool clearOnFirstInput = false)
|
|||
|
|
{
|
|||
|
|
_inputField = inputField;
|
|||
|
|
_manager = manager;
|
|||
|
|
_shouldClearOnFirstInput = clearOnFirstInput;
|
|||
|
|
_hasInputOccurred = false;
|
|||
|
|
|
|||
|
|
// 创建虚拟确认按钮(CustomKeyboard 需要)
|
|||
|
|
var btnGO = new GameObject("VirtualConfirmButton", typeof(Button));
|
|||
|
|
btnGO.transform.SetParent(this.transform, false);
|
|||
|
|
ConfirmButton = btnGO.GetComponent<Button>();
|
|||
|
|
|
|||
|
|
// 使用反射调用 manager 的 ConfirmInput 方法
|
|||
|
|
ConfirmButton.onClick.AddListener(() => {
|
|||
|
|
if (_manager != null)
|
|||
|
|
{
|
|||
|
|
var method = _manager.GetType().GetMethod("ConfirmInput");
|
|||
|
|
method?.Invoke(_manager, null);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
btnGO.SetActive(false); // 隐藏,只用于事件
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void OnKeyPressed(string key)
|
|||
|
|
{
|
|||
|
|
if (_inputField != null)
|
|||
|
|
{
|
|||
|
|
// 如果设置了首次清空且还未输入过,先清空
|
|||
|
|
if (_shouldClearOnFirstInput && !_hasInputOccurred)
|
|||
|
|
{
|
|||
|
|
_inputField.text = "";
|
|||
|
|
_hasInputOccurred = true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
_inputField.text += key;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void OnBackspacePressed()
|
|||
|
|
{
|
|||
|
|
if (_inputField != null && _inputField.text.Length > 0)
|
|||
|
|
{
|
|||
|
|
_inputField.text = _inputField.text.Substring(0, _inputField.text.Length - 1);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public void OnClearPressed()
|
|||
|
|
{
|
|||
|
|
if (_inputField != null)
|
|||
|
|
{
|
|||
|
|
_inputField.text = "";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|