在Android中使用StreamReader读取文本文件

时间:2018-08-09 08:16:30

标签: c# android unity3d streamreader android-assets

因此,我正在统一开发Visual Novel。该应用程序在PC中运行平稳,但现在我希望它在android中运行,但.txt文件中的内容未显示在屏幕上。我以为错误是无法加载StreamingAssets文件夹中的文本文件,我也不知道为什么。这是我的代码:

 void Start () {
    path = "jar:file://" + Application.dataPath + "!/assets/StreamingAssets/Dialogue0.txt";

    lines = new List<DialogueLine>();
    Example();
}

IEnumerator Example()
{
    if (path.Contains("://"))
    {
        var www = new WWW(path);
        yield return www;
        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError("Can't read");
        }
        LoadDialogue(www.text);
    }
    else
        LoadDialogue(path);
}



 void LoadDialogue(string filename)
{
    string line;
    StreamReader r = new StreamReader(filename);

    using (r)
    {
        do
        {
            line = r.ReadLine();
            if (line != null)
            {
                string[] lineData = line.Split('|');
                if (lineData[0] == "Player")
                {
                    DialogueLine lineEntry = new DialogueLine(lineData[0], "", 0, 0, "");
                    lineEntry.options = new string[lineData.Length - 1];
                    for (int i = 1; i < lineData.Length; i++)
                    {
                        lineEntry.options[i - 1] = lineData[i];
                    }
                    lines.Add(lineEntry);
                }
                else
                {
                    DialogueLine lineEntry = new DialogueLine(lineData[0], lineData[1], int.Parse(lineData[2]), int.Parse(lineData[3]), lineData[4]);
                    lines.Add(lineEntry);
                }
            }
        }
        while (line != null);
        r.Close();
    }
}

Path of my .txt file

Contents of my .txt file

1 个答案:

答案 0 :(得分:0)

只需将文件序列化为Appliction.persistentDataPath +文件名,然后轻松地从文件中读取文件即可。它将文件保存在Windows中的Windows(AppData / LocalLow / InYourUnityProject)中(在公司名称文件夹下)