Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write/read a txt file from sdcard in Unity?

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.

like image 808
Nghi Nguyen Avatar asked Oct 15 '25 04:10

Nghi Nguyen


1 Answers

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.

like image 120
Over17 Avatar answered Oct 17 '25 17:10

Over17



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!