Reputation: 121
I am a newbie in Unity. I have a problem like this.
I have high score of my game and i want to save it to a text file on mobile device. In this situation, i want to save that text file to my sdcard but i don't know how.
This code below shows how it reads and writes to a file. It works perfectly on my computer but it doesn't on emulator or real mobile device.
I think it's confused about the directory.
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 ();
}
Please help me about this. Thanks.
Upvotes: 4
Views: 5355
Reputation: 1071
Consider using PlayerPrefs for saving your highscore, for example:
PlayerPrefs.SetInt("Player Score", 10);
Update: use Application.persistentDataPath property if you want to save some data to SD card, this is the safest.
Upvotes: 2
Reputation: 535
PlayerPrefs may be a better option for saving high scores, but if you're looking to save to file then you may want to use Logcat when debugging your application as it may spew out helpful errors about exactly why it's failing to access/write to your location.
A couple hints:
You'll need to make sure your application has the Write External permission. Without it, Android will not let you write to the SD card.
You'll need to make sure that you in fact have an SD card in the device. You may want to check your emulator to make sure that it is a feature your emulator supports as well.
When accessing paths you'll need the file:// uri when dealing with Android.
Upvotes: 1