Unity中TMP输入框语法高亮实现问题求助
解决方案
1. 修复OutputField不更新的问题
原代码里的0.1秒协程延迟会导致高亮文本无法即时显示,直接同步更新即可,同时要确保outputField已在Unity Inspector面板正确赋值:
private void OnInputValueChanged(string text) { highlightedText = text.Replace("for", "<color=blue>for</color>") .Replace("int", "<color=green>int</color>") .Replace("float", "<color=green>float</color>") .Replace("bool", "<color=green>bool</color>") .Replace("void", "<color=green>void</color>") .Replace("mov", "<color=blue>mov</color>"); // 添加mov关键词高亮规则 Debug.Log(highlightedText); outputField.text = highlightedText; // 直接同步更新,无需延迟 }
2. 实现输入框自身的语法高亮(避免无限循环)
如果需要让inputField本身显示高亮文本,直接修改inputField.text会触发onValueChanged事件导致无限循环,推荐用以下两种方式解决:
方法一:使用SetTextWithoutNotify(更简洁)
TMP_InputField内置了SetTextWithoutNotify方法,设置文本时不会触发事件:
private void OnInputValueChanged(string text) { // 用正则匹配完整单词,避免误替换单词片段(比如不会把"move"里的"mov"高亮) string pattern = @"\b(for|int|float|bool|void|mov)\b"; highlightedText = Regex.Replace(text, pattern, match => { return match.Value is "for" or "mov" ? $"<color=blue>{match.Value}</color>" : $"<color=green>{match.Value}</color>"; }); inputField.SetTextWithoutNotify(highlightedText); // 同步更新outputField(如果需要的话) outputField.text = highlightedText; }
方法二:临时移除事件监听
修改文本前先移除监听,修改完成后重新添加:
private void OnInputValueChanged(string text) { // 临时移除监听,避免循环触发 inputField.onValueChanged.RemoveListener(OnInputValueChanged); string pattern = @"\b(for|int|float|bool|void|mov)\b"; highlightedText = Regex.Replace(text, pattern, match => { return match.Value is "for" or "mov" ? $"<color=blue>{match.Value}</color>" : $"<color=green>{match.Value}</color>"; }); inputField.text = highlightedText; // 重新添加监听 inputField.onValueChanged.AddListener(OnInputValueChanged); outputField.text = highlightedText; }
3. 关键优化点
- 用正则
\b匹配完整单词,避免错误高亮单词片段; - 若仅需更新
outputField,直接同步赋值即可,无需协程延迟;若要修改输入框自身,优先用SetTextWithoutNotify。
内容的提问来源于stack exchange,提问作者ryan trynda
相关产品推荐
相关产品推荐

