在Assets下创建一个文件夹,命名:Resources
将需要读取的txt文件放入该文件夹,
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
TextAsset t;
void Start()
{
//从Resources文件夹下,以TextAsset类型,读取命名MyText的文件,并赋值给t
t = Resources.Load<TextAsset>("MyText");
string s = t.text; //将t包含的文本赋值给s
Debug.Log(s); //测试结果
}
}
运行结果:
可能会遇到显示为空的情况,是因为txt文档的编码格式不是UTF-8格式,TextAsset 在解析txt文档的时候会把中文忽略掉。
解决方法一:将txt文件另存为UTF-8编码格式的txt文件;
解决方法二:修改系统默认的txt编码格式
附1:将txt逐行提取
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
TextAsset t;
void Start()
{
t = Resources.Load("MyText") as TextAsset;
string s = t.text;
List<string> sentences=new List<string>(); //句子的数组
int num = 0;
for (int i = 0; i < s.Length; i++)
{
string c = s.Substring(i, 1); //提取字符串中第i个字符,
if (c == "\n") //如果遇到换行符,跳过,
{
num += 1;
continue;
}
if (sentences.Count <= num) //创建新句子
{
sentences.Add(c);
}
else
{
sentences[sentences.Count-1] += c;
}
}
//测试结果
for (int i = 0; i < sentences.Count; i++)
{
Debug.Log(sentences[i]);
}
}
}
运行结果:
附2:解决中文text跳行问题
public static readonly string no_breaking_space = "\u00A0";
s_text = s_text.Replace(" ", no_breaking_space);
版权声明:本文为BIG_KENG原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。