次のコードを使用し、Unity エディターで「Time Out\n Fail」と入力すると、コードを読み込むときに、改行文字「\n」は読み取れませんが、エスケープ文字は「\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
}
}
上記の問題を解決するには2つの方法があります
- 入力文字列内のエスケープ文字は、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 } }
Multiline
機能を追加し、エディターで複数行にテキストを入力し、「\n」を使用せずに Enter キーを直接使用してテキストを折り返します。[SerializeField, Multiline] private string m_text;
- r、\n、\r\n、\t、\b などの他のエスケープ文字でも上記の方法を使用できます。