UGUI Text line header punctuation processing

How to deal with UGUI Text punctuation at the beginning of the line?

Before processing
Alt
After processing
Alt

Code:

private Text text;
    private void Start()
    {
    
    
        text = GetComponent<Text>();
    }

    void Update()
    {
    
    
        if (Input.GetKeyDown(KeyCode.Escape))
            StartCoroutine(RefillText());
    }
    
	//识别的标点符号,根据需要添加
    private readonly string symbolArr = "),。?!》::”、";
    IEnumerator RefillText()
    {
    
    
        //第一次处理
        string currentText = text.text;
        IList<UILineInfo> lines = text.cachedTextGenerator.lines;
        for (int i = 0; i < lines.Count; i++)
        {
    
    
            if (symbolArr.Contains(currentText[lines[i].startCharIdx].ToString()))
            {
    
    
                currentText = currentText.Insert(lines[i].startCharIdx - 1, "\n");
            }
        }
        text.text = currentText;
        
        yield return null;
        
        //第二次处理,防止因增加换行字符多出一行
        string newText = currentText;
        IList<UILineInfo> newLines = text.cachedTextGenerator.lines;
        if (symbols.Contains(newText[newLines[newLines.Count - 1].startCharIdx].ToString()))
        {
    
    
            newText = newText.Insert(newLines[newLines.Count - 1].startCharIdx - 1, "\n");
        }
        text.text = newText;
    }

There may be some things that were not carefully considered, and it should be fine with a few changes ( ̄▽ ̄)"

Guess you like

Origin blog.csdn.net/weixin_38359813/article/details/103669636