【问题标题】:Unity 3D Android and FileUnity 3D Android 和文件
【发布时间】:2016-05-19 08:23:25
【问题描述】:

我在使用 Android 和 Unity 3D 时遇到问题。我有一个文件读取代码。当我把我的代码放在电脑上时,它就可以工作了。但是,我的代码不适用于 Android(移动)。我怎么解决这个问题?谢谢。

FileInfo theSourceFile = new FileInfo(filename);
    if (System.IO.File.Exists(fname))
    {
        StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(string);
    }

编辑更新代码

string filename = "file.txt";
FileInfo theSourceFile = new FileInfo(filename);
filename = Application.persistentDataPath + "/"+filename;
System.IO.File.WriteAllText(filename,"Test");
    if (System.IO.File.Exists(filename))
    {
        StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(string);
    }

【问题讨论】:

  • filename 在哪里定义?它是什么样子的?发布网址是怎样的

标签: android file mobile unity3d apk


【解决方案1】:

您需要更改 android 设备的构建设置。 更改配置 >> 对外部(sd 卡)的写访问。

如果不是,您的应用指向内部路径,您需要在您的 android 设备中获得 root 权限。

【讨论】:

    【解决方案2】:

    您必须在 Android 上使用 Application.persistentDataPath 才能读取任何内容。

    将其更改为 string filename = Application.persistentDataPath + "/file.txt";,您的代码应该可以正常工作。

    请记住,在读取功能起作用之前,您必须先写入目录。所以file.txt必须首先存在于Application.persistentDataPath中。

    例如

    string filename = Application.persistentDataPath + "/file.txt";
    System.IO.File.WriteAllText(filename,"Test");
    

    编辑:

    您的新代码仍然无法正常工作,因为您在 filename = Application.persistentDataPath + "/"+filename; 之前有 FileInfo theSourceFile = new FileInfo(filename);。这意味着文件名仍然无效有效。注意您的脚本执行顺序。切换后,它可以在我的Android上运行。下面是整个代码。

    string filename = "file.txt";
    filename = Application.persistentDataPath + "/" + filename;
    System.IO.FileInfo theSourceFile = new System.IO.FileInfo(filename);
    System.IO.File.WriteAllText(filename, "Test");
    if (System.IO.File.Exists(filename))
    {
        System.IO.StreamReader reader = theSourceFile.OpenText();
        string text = reader.ReadLine();
        print(text);
    }
    

    【讨论】:

    • 我收到“文件不存在”消息。
    • @Leo 您必须先写入该文件,然后才能使用它。看看我的编辑。使用 File.write 并确保在我的答案中使用正确的 url。然后您可以使用 File.Read.... 阅读它。
    • 我做到了,但在我的手机上仍然无法使用。
    • @Leo 将 Edit 放入您的问题中并发布您的新/当前代码不起作用。编辑并将其添加到您的问题中。不要删除您的旧帖子。
    • @Leo 即使在您编辑之后,由于您放置代码的顺序,仍然存在问题。我复制了你的新代码并更正了它。它现在应该可以工作了。在我的回答中的编辑下查看工作代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 2016-11-09
    • 2016-08-19
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多