Unity中C#读取文本文件时自动换行功能失效问题
问题:Unity文本框无法识别换行符,直接显示"\n"
当通过StreamReader读取包含换行符的文本文件,赋值给_text后,用逐字符拼接的方式更新UI文本时,文本框直接显示\n或\r\n而非实际换行,代码如下:
foreach (var symbol in _text) { dialogueRunning = true; audioSource.clip = _soundArray[Random.Range(0, 2)]; textGameObjects.text += symbol; audioSource.Play(); yield return new WaitForSeconds(0.05f); }
原因分析
从文本文件读取时,\n被解析成了两个独立的字符(\和n),而非转义后的换行符。这通常是因为文本文件中手动输入了\n字符串,而非实际按下回车键产生的换行;或者读取时未正确处理转义序列。
解决方法
方法一:预处理文本替换转义字符
在逐字符拼接前,先将读取到的转义字符串替换为实际换行符:
// 替换\\n为\n(读取后文件中的\n会变成\\n) _text = _text.Replace("\\n", "\n"); // 若存在\\r\\n的情况也一并处理 _text = _text.Replace("\\r\\n", "\n"); // 执行原有的逐字符拼接逻辑 foreach (var symbol in _text) { dialogueRunning = true; audioSource.clip = _soundArray[Random.Range(0, 2)]; textGameObjects.text += symbol; audioSource.Play(); yield return new WaitForSeconds(0.05f); }
方法二:修改文本文件的换行方式
打开文本文件,直接按回车键添加换行,而非手动输入\n字符串。这样StreamReader读取时会自动识别为换行符,无需额外处理。
方法三:逐字符判断处理
在循环中识别转义序列,直接替换为换行符:
for (int i = 0; i < _text.Length; i++) { dialogueRunning = true; char currentChar = _text[i]; // 识别\\n转义序列 if (currentChar == '\\' && i + 1 < _text.Length && _text[i+1] == 'n') { textGameObjects.text += '\n'; i++; // 跳过下一个'n'字符 } // 识别\\r\\n转义序列 else if (currentChar == '\\' && i + 2 < _text.Length && _text[i+1] == 'r' && _text[i+2] == 'n') { textGameObjects.text += '\n'; i += 2; // 跳过'r'和'n'字符 } else { textGameObjects.text += currentChar; } audioSource.clip = _soundArray[Random.Range(0, 2)]; audioSource.Play(); yield return new WaitForSeconds(0.05f); }
内容的提问来源于stack exchange,提问作者Арсен
相关产品推荐
相关产品推荐

