0 votes

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. :)

asked Jun 27, 2019 in Engine by bodicpen (94 points)

1 Answer

+1 vote
Best answer

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()
answered Jun 27, 2019 by kidscancode (17,704 points)
selected Jun 28, 2019 by bodicpen

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!

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

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?

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.