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

Unity运行时动态绑定Text Mesh Pro输入框On End Edit事件求助

在Runtime绑定TextMeshPro输入框的OnEndEdit事件到指定方法

嘿,我之前做Unity项目时也碰到过一模一样的问题,给你分享一套亲测有效的解决方案:

核心实现步骤与代码示例

首先得确保你的脚本引用了TextMeshPro的命名空间,然后分三步操作:

  1. 获取组件实例:要么在Inspector面板拖拽赋值TMP_InputField,要么在Runtime通过FindObjectOfType、GetComponent等方式查找;同时拿到你的PlayerConnectionManager组件实例(假设它挂载在场景中的某个GameObject上)。
  2. 匹配方法签名:PlayerConnectionManager里的PressedButton方法必须和OnEndEdit的委托签名一致——也就是要接收一个string类型的参数(输入框的文本内容会自动传进来),并且方法的访问修饰符是public。
  3. 绑定事件监听:调用onEndEdit.AddListener()把目标方法关联到输入框的结束编辑事件上。

完整代码示例:

using UnityEngine;
using TMPro;

public class InputFieldEventHandler : MonoBehaviour
{
    // 可在Inspector面板直接拖拽赋值TMP输入框
    [SerializeField] private TMP_InputField _playerInputField;
    private PlayerConnectionManager _connectionManager;

    void Start()
    {
        // 根据你的项目结构获取PlayerConnectionManager实例,这里用FindObjectOfType做示例
        _connectionManager = FindObjectOfType<PlayerConnectionManager>();

        if (_playerInputField != null && _connectionManager != null)
        {
            // 直接绑定OnEndEdit事件到PressedButton方法
            _playerInputField.onEndEdit.AddListener(_connectionManager.PressedButton);

            // 如果需要对输入文本做预处理,也可以用lambda表达式包装
            // _playerInputField.onEndEdit.AddListener((inputText) => {
            //     string cleanedText = inputText.Trim();
            //     _connectionManager.PressedButton(cleanedText);
            // });
        }
        else
        {
            Debug.LogError("找不到TMP输入框或PlayerConnectionManager实例,请检查组件挂载情况!");
        }
    }

    // 场景切换或对象销毁时移除监听,避免内存泄漏
    void OnDestroy()
    {
        if (_playerInputField != null && _connectionManager != null)
        {
            _playerInputField.onEndEdit.RemoveListener(_connectionManager.PressedButton);
        }
    }
}

对应的PlayerConnectionManager方法示例:

public class PlayerConnectionManager : MonoBehaviour
{
    // 方法签名必须匹配:接收string参数,访问修饰符为public
    public void PressedButton(string inputContent)
    {
        // 这里编写你的业务逻辑,比如处理输入的房间号、玩家ID等
        Debug.Log($"输入结束,内容为:{inputContent}");
    }
}

额外注意事项

  • 如果是动态生成的TMP输入框,只需要在生成代码执行完成后,立即调用上述绑定逻辑即可。
  • 一定要保证方法签名完全匹配,否则Unity会在控制台抛出委托不匹配的错误。
  • 移除监听是个好习惯,尤其是在场景切换或者对象销毁时,能避免不必要的内存泄漏。

编辑器中On End Edit事件的截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:48:45