You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中TMP_InputField输入后自动切换聚焦失效问题求助

Unity TMP_InputField 自动聚焦第二个输入框问题解决

原代码问题分析

  • 仅调用Select()无法真正激活输入框,必须配合ActivateInputField()才能让输入框进入可输入状态
  • Update轮询会重复触发切换逻辑,导致输入框状态冲突
  • 缺少切换状态标记,无法控制仅在文本从空变非空时触发一次切换

修复后的Update版本代码

using UnityEngine;
using TMPro;

public class FocusBox : MonoBehaviour
{
    public TMP_InputField b1;
    public TMP_InputField b2;
    private bool hasSwitched = false; // 标记是否已完成切换,避免重复触发

    private void Update()
    {
        if (b1.isFocused && !hasSwitched)
        {
            if (b1.text.Length > 0)
            {
                b1.DeactivateInputField();
                b2.Select();
                b2.ActivateInputField(); // 关键:激活输入框的可输入状态
                hasSwitched = true;
            }
        }

        // 当b1失去焦点或文本清空时,重置标记允许再次触发切换
        if (!b1.isFocused || b1.text.Length == 0)
        {
            hasSwitched = false;
        }
    }
}

更优的事件驱动版本(推荐)

通过onValueChanged事件监听文本变化,无需每帧轮询,性能更高效:

using UnityEngine;
using TMPro;

public class FocusBox : MonoBehaviour
{
    public TMP_InputField b1;
    public TMP_InputField b2;
    private bool hasSwitched = false;

    private void OnEnable()
    {
        // 注册文本变化事件
        b1.onValueChanged.AddListener(OnB1TextChanged);
    }

    private void OnDisable()
    {
        // 移除事件避免内存泄漏
        b1.onValueChanged.RemoveListener(OnB1TextChanged);
    }

    private void OnB1TextChanged(string newText)
    {
        if (b1.isFocused && newText.Length > 0 && !hasSwitched)
        {
            b1.DeactivateInputField();
            b2.Select();
            b2.ActivateInputField();
            hasSwitched = true;
        }

        // 文本清空时重置标记
        if (newText.Length == 0)
        {
            hasSwitched = false;
        }
    }
}

关键注意事项

  • 必须在Inspector面板中为脚本的b1和b2字段赋值对应的TMP_InputField组件
  • 移动端测试时,确保项目输入系统设置支持UI键盘输入
  • 事件驱动方式响应更精准,性能更优,建议优先使用

内容的提问来源于stack exchange,提问作者Craving_gold

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 16:10:29