统一的语法荧光笔

问题描述 投票:0回答:1

这是代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.Text.RegularExpressions;
public class syntaxHighlter : MonoBehaviour
{
    [SerializeField] private TMP_InputField inputField;
    [SerializeField] private TextMeshProUGUI outputField;
    string highlightedText;

    private void Start()
    {
        inputField.onValueChanged.AddListener(OnInputValueChanged);
    }

    private IEnumerator UpdateOutputField(string text)
    {
        yield return new WaitForSeconds(0.1f); // delay for 0.1 seconds
        outputField.text = text;
    }

    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>");
        Debug.Log(highlightedText);
        
        StartCoroutine(UpdateOutputField(highlightedText));
    }
}

我正在尝试在 TMP 输入字段中制作 syntaxHighliter,例如,如果我输入单词“mov”,它会立即将颜色更改为蓝色,但显然当我在这里修改时,outputfield.text 没有改变。我尝试直接更改输入字段但创建了一个无限循环,尝试修改输入字段导致无限循环

c# unity3d syntax-highlighting textmeshpro
1个回答
0
投票

你正在做的事情最终会陷入无限更新循环

  • a) 因为再次更改

    text
    属性将调用
    onValueChanged

    -> 你宁愿在这里使用

    SetTextWithoutNotify
    以免再次调用
    onValueChanged

  • 和 b) 因为

    <color=green>int</color>
    也包含
    int
    并且将在下一次运行中产生
    <color=green><color=green>int</color></color>

-> 你宁愿替换

(" int ", "<color=green>int</color>")
等,所以只有当你的关键字前后有空格

所以这应该没问题

private void OnInputValueChanged(string text)
{
    text = 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>");

    Debug.Log(text);
    
    inputField.SetTextWithoutNotify(text);
}
© www.soinside.com 2019 - 2024. All rights reserved.