When Unity enters a string in the editor, the input of escape characters

When using the following code, and then entering "Time Out\n Fail" in the Unity editor, when reading in the code, the newline character "\n" cannot be read, but the escape character is read "\n"

using UnityEngine;

public class TestText : MonoBehaviour {

    [SerializeField] private string m_text;

    void Start() {
        Debug.Log(m_text.IndexOf("\n")); // -1
        Debug.Log(m_text.IndexOf("\\n")); // 8
    }
}

There are two ways to solve the above problem

  1. Any escape characters in the input string can be converted using Regex.Unescape.
    using System.Text.RegularExpressions;
    using UnityEngine;
    
    public class TestText : MonoBehaviour {
    
        [SerializeField] private string m_text;
    
        void Start() {
            m_text = Regex.Unescape(m_text);
            Debug.Log(m_text.IndexOf("\n")); // 8
            Debug.Log(m_text.IndexOf("\\n")); // -1
        }
    }
  2. Add Multilinethe feature , enter text in multiple lines in the editor, use the Enter key directly to wrap the text without using "\n".
    [SerializeField, Multiline] private string m_text;
  • Other escape characters can also use the above methods, such as: r, \n, \r\n, \t, \b

Guess you like

Origin blog.csdn.net/kingBook928/article/details/125507177