2015-04-23 213 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。