如何在Unity的Android构建中读取文本文件?

4

在我将游戏打包为.apk文件后,在Android手机上读取StreamingAsset文件夹中存储的文本文件一直很麻烦。

我知道在Android系统中,要访问这些文件需要使用不同的路径:

"jar:file://" + Application.dataPath + "!/assets" + fileName;

并将其存储到WWW类中。我尝试了很多方法,但是似乎没有什么作用,因为我现在完全迷失了方向。我的代码如下:

void Awake(){
    string filePath = "jar:file://" + Application.dataPath + "!/assets" + fileName;
    // Reads our text file and stores it in the array

    string[][] Level = readFile (filePath);
}

// Reads our level text file and stores the information in a jagged array, then returns that array
string[][] readFile(string file){
    WWW loadFile = new WWW (file);
    while (!loadFile.isDone) {}
    string text = System.IO.File.ReadAllText(loadFile.text);
    string[] lines = Regex.Split(text, "\r\n");
    int rows = lines.Length;

    string[][] levelBase = new string[rows][];
    for (int i = 0; i < lines.Length; i++)  {
        string[] stringsOfLine = Regex.Split(lines[i], " ");
        levelBase[i] = stringsOfLine;
    }
    return levelBase;
}
2个回答

0
你可以使用Streamreader来实现这个功能:
    List<string> lines = new List<string>();
    using (StreamReader reader = new StreamReader("file.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
        lines.Add(line); 
        }
    }

-1

这行代码 string text = System.IO.File.ReadAllText(loadFile.text); 是错误的:

  • loadFile.text 已经包含了你正在尝试使用 System.IO.File.ReadAllText 打开的文件的内容。
  • 另外,在 Android 上,你不能使用 System.IO.File.ReadAllText 方法访问 StreamingAssets 中的文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接