我正试图从外部源读取Unity中的文件而没有运气。 为了更清楚,我在开发游戏时可以使用StreamWriter和StreamReader轻松读取和写入文件。
问题是构建游戏后不再想要读取文件了。 问题是在构建中我没有资源文件夹和position.txt文件。
所以我试着把文件放在c下:用这种方式调用函数ReadFromFile(@"C:\test\position.txt");
它仍然可以在开发中运行,但不能在构建之后
string path = Application.dataPath+"/Resources/position.txt";
ReadFromFile(path);
public bool ReadFromFile(string fileName)
{
try
{
string line;
StreamReader theReader = new StreamReader(fileName, Encoding.Default);
using (theReader)
{
do
{
line = theReader.ReadLine();
if (line != null)
{
string[] entries = line.Split(',');
switch (entries[0])
{
case "1":
Console.WriteLine("Case 1");
cube1 = GameObject.Find("Cube1");
cube1.GetComponent<Renderer>().material.color = Color.red;
StartCoroutine(RotateCoroutine(new Vector3(0, 90, 0), 2.0f, cube1));
break;
case "2":
Console.WriteLine("Case 2");
cube2 = GameObject.Find("Cube2");
cube2.GetComponent<Renderer>().material.color = Color.red;
StartCoroutine(RotateCoroutine(new Vector3(0, 90, 0), 2.0f, cube2));
break;
case "3":
Console.WriteLine("Case 3");
cube3 = GameObject.Find("Cube3");
cube3.GetComponent<Renderer>().material.color = Color.red;
StartCoroutine(RotateCoroutine(new Vector3(0, 90, 0), 2.0f, cube3));
break;
default:
Console.WriteLine("Default case");
break;
}
}
}
while (line != null);
theReader.Close();
return true;
}
}
catch (Exception e)
{
Console.WriteLine("{0}\n", e.Message);
return false;
}
}
Can someone give me some hints to make it work?
答案 0 :(得分:2)
您可以使用TextAsset
TextAsset txt = (TextAsset)Resources.Load("position", typeof(TextAsset));
然后将文本拆分为行
List<string> lines = new List<string>(txt.text.Split('\n'));
如果您想要跨平台兼容,也可以用System.Environment.NewLine替换'\ n'