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

Unity中如何将TextMeshPro输入框文本传入气泡对话框?

问题解决:Unity中TextMeshPro输入框空引用错误

空引用错误的核心原因是inputText变量从未被赋值(没有关联到场景中的实际TextMeshPro组件),调用inputText.text时自然会报错。以下是几种直接可行的解决办法:

方案1:直接使用回调参数(最简便)

你的ReadStringInput方法已经通过参数Input接收了输入框的文本,完全不需要额外的inputText变量,直接用这个参数即可:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class PlayerTalk : MonoBehaviour
{
    [SerializeField] private Transform playerTransform;

    public void ReadStringInput(string input)
    {
        ChatBubble.Create(playerTransform, new Vector3(0, 0), ChatBubble.IconType.Neutral, input);
    }
}

编辑器绑定步骤:

  • 选中场景中的TextMeshPro输入框
  • 在Inspector的TMP Input Field组件中,找到On End Edit事件列表
  • 点击+号,将挂载PlayerTalk脚本的物体拖入对象框
  • 在下拉菜单选择PlayerTalk -> ReadStringInput(string)

这样输入完成按回车时,输入框会自动把文本传递给方法,彻底避免空引用。

方案2:正确关联TMP输入框组件

如果需要通过变量主动获取输入框文本,需修正变量类型并完成赋值:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class PlayerTalk : MonoBehaviour
{
    [SerializeField] private Transform playerTransform;
    // 使用TMP专属输入框类型,并设为可序列化方便Inspector赋值
    [SerializeField] private TMP_InputField chatInputField;

    public void ReadStringInput(string input)
    {
        ChatBubble.Create(playerTransform, new Vector3(0, 0), ChatBubble.IconType.Neutral, chatInputField.text);
    }

    // 可选:自动查找输入框(场景中仅一个TMP输入框时可用)
    void Start()
    {
        if (chatInputField == null)
        {
            chatInputField = FindObjectOfType<TMP_InputField>();
        }
    }
}

赋值步骤:

选中挂载PlayerTalk脚本的物体,将场景中的TextMeshPro输入框拖入Inspector面板的chatInputField变量框中。

关键注意事项

  • 不要混用普通InputField和TMP_InputField,TextMeshPro项目需全程使用TMP系列组件
  • 空引用的本质是变量未指向任何实际存在的组件,务必确保变量通过Inspector拖入或代码查找完成赋值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:32:50