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:
- 创建新脚本
CustomTMPInputField.cs:
using TMPro; public class CustomTMPInputField : TMP_InputField { // 公开方法调用基类的protected Append public void PublicAppend(string input) { Append(input); } }
- 将场景中原有
TMP_InputField组件替换为CustomTMPInputField(删除原组件,添加自定义组件并保留原有配置) - 修改调用代码:
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
相关产品推荐
相关产品推荐

