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

Unity中无法访问TMP_InputField.Append方法的问题求助

解决TMP_InputField.Append方法无法访问的问题

因为TMP_InputField.Append(string)是protected级别的方法,外部类无法直接调用,这里提供三种可行的解决方式:

方法一:直接拼接文本(最简单)

不需要调用Append方法,直接通过修改text属性实现追加效果,同时可按需维护光标位置:

using TMPro;
public TMP_InputField inputField;

if (selectedButton != null && Input.GetKeyDown(KeyCode.F1))
{
    TextMeshProUGUI buttonText = buttons[(int)selectedButton].GetComponentInChildren<TextMeshProUGUI>();
    string textOnButton = buttonText.text;
    
    // 追加文本
    inputField.text += textOnButton;
    // 让光标移动到文本末尾(可选)
    inputField.caretPosition = inputField.text.Length;
}

方法二:继承TMP_InputField扩展公开方法

创建自定义输入字段类,继承TMP_InputField并封装公开方法调用基类的Append:

  1. 创建新脚本CustomTMPInputField.cs:
using TMPro;

public class CustomTMPInputField : TMP_InputField
{
    // 公开方法调用基类的protected Append
    public void PublicAppend(string input)
    {
        Append(input);
    }
}
  1. 将场景中原有TMP_InputField组件替换为CustomTMPInputField(删除原组件,添加自定义组件并保留原有配置)
  2. 修改调用代码:
using TMPro;
public CustomTMPInputField inputField; // 类型改为自定义类

if (selectedButton != null && Input.GetKeyDown(KeyCode.F1))
{
    TextMeshProUGUI buttonText = buttons[(int)selectedButton].GetComponentInChildren<TextMeshProUGUI>();
    string textOnButton = buttonText.text;
    
    inputField.PublicAppend(textOnButton);
}

方法三:通过反射调用(不推荐,仅应急)

利用反射突破访问权限限制,但该方式依赖TMPro内部实现,后续版本更新可能失效:

using System.Reflection;
using TMPro;
public TMP_InputField inputField;

if (selectedButton != null && Input.GetKeyDown(KeyCode.F1))
{
    TextMeshProUGUI buttonText = buttons[(int)selectedButton].GetComponentInChildren<TextMeshProUGUI>();
    string textOnButton = buttonText.text;
    
    // 通过反射获取Append方法
    MethodInfo appendMethod = typeof(TMP_InputField).GetMethod("Append", BindingFlags.Instance | BindingFlags.NonPublic);
    appendMethod?.Invoke(inputField, new object[] { textOnButton });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 23:12:49