【游戏开发】Unity中的txt文本读取及显示

如何使用脚本将一个txt文本逐行读入Unity并打印?

命名空间

首先需要在脚本中包含using System.IO;
这个不是Unity的,而是C#中的,用于处理文件读写。包含这个,才能使用进行文件读取所需要的类和方法。
之后,加上用于操作Unity中UI控件的using UnityEngine.UI;
准备完毕。

类对象

下一步,在类中定义public Text myText;然后在Unity窗口操作,使其引用一个游戏中的文本框,便于之后修改并显示文本。
此外,需要定义private string fileName;用于存储txt文件的相对路径;定义private string[] strs;用于存储读取的文本内容。

txt文本文件

将需要的文本文件写好,每一句用换行符分隔。
txt文件存储的位置随意,只要位于工程文件夹(即用本工程名称命名的文件夹)内即可。
注意记住该位置相对于工程文件夹的相对位置。
如我在工程文件夹下新建文件夹命名为“Text”,并存储文件“A.txt”在文件夹内。

脚本

脚本逻辑如下:

  1. 首先中为对象赋初值:fileName = "Text/A.txt"; //读取文件位置
  2. 然后开始读取并存储文本:strs = File.ReadAllLines(fileName); //将文件内容存入strs
  3. 最后将句子显示在文本框中:foreach (string str in strs){myText.text += str; myText.text += "\n";} //更新文本框内容

完整代码

ShowText
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;

public class ShowText : MonoBehaviour
{
public Text myText;

private string fileName;
private string[] strs;
// Start is called before the first frame update
void Start()
{
fileName = "Text/A.txt";
strs = File.ReadAllLines(fileName);

myText.text = "";

foreach(string str in strs)
{
myText.text += str;
myText.text += "\n";
}
}

}

Unity中效果