【问题标题】:how to read text files on android builds for Unity?如何在 Unity 的 android 版本上读取文本文件?
【发布时间】:2015-05-11 23:38:09
【问题描述】:

当我将游戏构建为 .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;
}

【问题讨论】:

    标签: c# android unity3d


    【解决方案1】:

    您可以为此使用流式阅读器:

        List<string> lines = new List<string>();
        using (StreamReader reader = new StreamReader("file.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
            lines.Add(line); 
            }
        }
    

    【讨论】:

      【解决方案2】:

      string text = System.IO.File.ReadAllText(loadFile.text);这行写错了:

      • loadFile.text 已包含您尝试使用 System.IO.File.ReadAllText 打开的文件的内容
      • 此外,您不能使用 System.IO.File.ReadAllText 方法从 Android 上的 StreamingAssets 访问文件。

      【讨论】:

        猜你喜欢
        • 2015-03-17
        • 1970-01-01
        • 2012-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多