2015-04-23 215 views
2

我是Unity的新手。我有这样的问题。如何在Unity中从sdcard写入/读取txt文件?

我的游戏分数很高,我想将它保存到移动设备上的文本文件中。在这种情况下,我想将该文本文件保存到我的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(); 
} 

请帮我了解一下。 谢谢。

回答

1

PlayerPrefs可能是一个更好的选择来保存高分,但是如果您希望保存到文件中,那么在调试应用程序时可能需要使用Logcat,因为它可能会发出有关为什么无法访问的有用错误/写入您的位置。

一对夫妇提示:

  • 你需要确保你的应用程序有写权限的外部。没有它,Android不会让你写入SD卡。

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

  • 访问路径时,在处理Android时需要使用file:// uri。