Unity C#中切换TMP InputField时虚拟键盘消失的解决诉求
解决Unity中切换TMP InputField时虚拟键盘消失的问题
这个问题本质是Unity默认会在TMP InputField失去焦点时隐藏虚拟键盘,切换输入框时前一个输入框的失焦事件会先触发,导致键盘隐藏,后一个输入框获得焦点时的键盘唤起逻辑可能被系统或Unity默认行为覆盖。下面是两种可行的解决方法:
方法1:输入框事件监听+手动控制键盘
给每个需要保持键盘的TMP InputField挂载以下脚本,通过监听失焦和选中事件,强制在切换时保持键盘显示:
using UnityEngine; using TMPro; public class KeepKeyboardOnSwitch : MonoBehaviour { private TMP_InputField _inputField; private bool _isSwitchingInput; void Awake() { _inputField = GetComponent<TMP_InputField>(); if (_inputField == null) { Debug.LogError("当前物体没有挂载TMP_InputField组件!"); return; } // 绑定输入框事件 _inputField.onEndEdit.AddListener(OnInputEnd); _inputField.onSelect.AddListener(OnInputSelect); } void OnInputEnd(string inputText) { // 如果是主动切换输入框,强制保持键盘显示 if (_isSwitchingInput) { #if UNITY_ANDROID || UNITY_IOS TouchScreenKeyboard.Open(inputText, _inputField.inputType, false, false, false, false); #endif _isSwitchingInput = false; } } void OnInputSelect(string inputText) { // 选中当前输入框时,直接唤起键盘 #if UNITY_ANDROID || UNITY_IOS TouchScreenKeyboard.Open(inputText, _inputField.inputType, false, false, false, false); #endif } // 外部调用此方法标记正在切换输入框 public void MarkAsSwitching() { _isSwitchingInput = true; } }
使用步骤:
- 将脚本挂载到所有需要保持键盘的TMP InputField上
- 如果通过按钮或导航键切换输入框,在切换逻辑中先调用前一个输入框的
MarkAsSwitching(),再选中下一个输入框。示例代码:
public TMP_InputField inputA; public TMP_InputField inputB; public void SwitchToInputB() { inputA.GetComponent<KeepKeyboardOnSwitch>().MarkAsSwitching(); inputB.Select(); }
方法2:全局监听输入框选中状态
创建一个全局管理器,监听EventSystem的选中对象变化,自动为新选中的输入框唤起键盘:
using UnityEngine; using UnityEngine.EventSystems; using TMPro; public class GlobalKeyboardPersist : MonoBehaviour { private TMP_InputField _lastActiveInput; void Update() { GameObject currentSelected = EventSystem.current.currentSelectedGameObject; if (currentSelected == null) { _lastActiveInput = null; return; } TMP_InputField currentInput = currentSelected.GetComponent<TMP_InputField>(); if (currentInput != null && currentInput != _lastActiveInput) { // 切换到新输入框,强制唤起键盘 #if UNITY_ANDROID || UNITY_IOS TouchScreenKeyboard.Open(currentInput.text, currentInput.inputType, false, false, false, false); #endif _lastActiveInput = currentInput; } } }
使用步骤:
- 将脚本挂载到场景中的任意空物体上
- 确保场景中有
EventSystem组件(默认UI模板会自动添加)
注意事项
- 仅在Android/iOS平台测试有效,PC平台无虚拟键盘
- 根据输入框类型(密码、数字等)调整
TouchScreenKeyboard.Open()的参数,比如密码输入需把第四个参数设为true - 确保TMP InputField的
interactable和enabled属性均为true
内容的提问来源于stack exchange,提问作者Ameerah Hasan
相关产品推荐
相关产品推荐

