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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With