Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Unity中从SD卡写入/读取txt文件?_C#_Android_File_Unity3d_Read Write - Fatal编程技术网

C# 如何在Unity中从SD卡写入/读取txt文件?

C# 如何在Unity中从SD卡写入/读取txt文件?,c#,android,file,unity3d,read-write,C#,Android,File,Unity3d,Read Write,我是Unity的新手。我有这样的问题 我的游戏分数很高,我想把它保存到移动设备上的文本文件中。在这种情况下,我想将该文本文件保存到SD卡,但不知道如何保存 下面的代码显示了它如何读取和写入文件。它在我的电脑上运行得很好,但在模拟器或真正的移动设备上却不行 我想它把目录弄糊涂了 void writeHighScore() { string path = "\\sdcard\\colorbounce\\highscore.txt"; int highscore = 0; //

我是Unity的新手。我有这样的问题

我的游戏分数很高,我想把它保存到移动设备上的文本文件中。在这种情况下,我想将该文本文件保存到SD卡,但不知道如何保存

下面的代码显示了它如何读取和写入文件。它在我的电脑上运行得很好,但在模拟器或真正的移动设备上却不行

我想它把目录弄糊涂了

void writeHighScore() {
    string path = "\\sdcard\\colorbounce\\highscore.txt";
    int highscore = 0;
    // This text is added only once to the file. 

    if (!File.Exists(path)) 
    {
        System.IO.Directory.CreateDirectory("\\sdcard\\colorbounce\\");
        // Create a file to write to. 
        using (StreamWriter sw = File.CreateText(path)) 
        {
            sw.WriteLine(score);
        }   
    }
    // Open the file to read from. 
    using (StreamReader sr = File.OpenText(path)) 
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) 
        {
            highscore = int.Parse(s);
        }
    }
    if (score > highscore) {
        // This text is always added, making the file longer over time 
        // if it is not deleted. 
        using (StreamWriter sw = File.AppendText(path)) 
        {
            sw.WriteLine(highscore);
        }
    }
    highScoreText.text = highscore.ToString ();
}
请帮我解决这个问题。 谢谢。

考虑使用以保存您的高分,例如:


PlayerPrefs.SetInt(“玩家分数”,10)PlayerPrefs可能是保存高分的更好选项,但如果您希望保存到文件,则在调试应用程序时可能需要使用Logcat,因为它可能会抛出有关无法访问/写入您的位置的确切原因的有用错误

几点提示:

  • 您需要确保您的应用程序具有外部写入权限。如果没有它,Android将不允许您写入SD卡

  • 您需要确保设备中确实有SD卡。您可能需要检查您的仿真器,以确保它也是您的仿真器支持的功能

  • 在访问路径时,在处理Android时需要文件://uri