How to save game progress on android?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bodicpen

Hello! So I’m developing an android game but I’ve ran into an issue. I’ve used a singleton node (the one you put in the autoload) to store variables in which all the scene can get data from (The data are the “high scores”). And this worked but when I tried it on android, the “high scores” were not saved when I relaunched the game i.e. the high scores were set back to 0 rather than my scores before I relaunched it.

I’ve looked through video tutorials in YouTube but they were really overwhelming as the code weren’t explained why they were there in the first place, and besides, some people have reported that the tutorials only work for PC and not on android. I’ve read the Godot documentation as well but it talks about grouping together certain objects and serializing stuff but all I wanted to be saved were variables for the high scores that are going to be rewritten whenever the new score is higher than the high scores and not really an object.

I’m fairly a beginner in Godot and I’ve never used any save system before so bear with my ignorance. Thank you so much!

P.S. Pseudo-code is highly appreciated but not necessary. :slight_smile:

:bust_in_silhouette: Reply From: kidscancode

First, make sure you’re saving in the right place. User data needs to be saved in user://. On Android, this will be the only writeable path.

Here’s some example code to load and save a high score. It should get you started:

var score_file = "user://highscore.save"
var highscore

func load_score():
    var f = File.new()
    if f.file_exists(score_file):
        f.open(score_file, File.READ)
        highscore = f.get_var()
        f.close()
    else:
        highscore = 0

func save_score():
    var f = File.new()
    f.open(score_file, File.WRITE)
    f.store_var(highscore)
    f.close()

Oh my god it’s you! I’ve been following you on Youtube in your tutorials and you were the one who got me started on Godot! I will try your sample code and will check back if I get it right. Thank you!

bodicpen | 2019-06-28 05:46

It worked! I knew there was a simpler method than those youtube videos. Thank you so much!

bodicpen | 2019-06-28 06:18

Just a question though, in your load_score() function, why would you create a new file then check if that file exists? I assume that we are checking if there are saved data but even if there is not, there would be because we just created a new file before we check?

bodicpen | 2019-06-28 07:59

The line var f = File.new() creates a new File object, not a new file on the disk. This File object is how you interact with files on the disk.

jandrewlong | 2019-06-28 13:48

not working apk export.

Mrtoxa42 | 2021-12-20 19:25