My ConfigFile code is not working as planned

Godot Version

4.2

Question

#Autoload Script
extends Node

var config_file = ConfigFile.new()
var highscore = 0

func load_score():
    config_file.load(path)
    #auto in this case refers to the autoload itself
    auto.highscore = config_file.get_value("try",  "highscore", 0)

func save_score():
    config_file.set_value("try", "highscore", auto.highscore)
    config_file.save("user://hello.cfg")

I would please like to ask about why this code is not working.

You see I start my game with my first scene loading my highscore (using load_score function inside the autoload script which uses a ConfigFile instance/config_file) and that works fine.

But then the problem rises when later in another scene I call the save_score function from the autoload script which saves my highscore as planned except it deletes the other things in the .cfg and only leaves the highscore.

The problem here is that why is it not only updating the highscore and leaving the other things in the .cfg file without having to delete them since config_file was declared globally in the autoload script and should not be forgetting what it is holding through scenes.

(One thing to remember is that each time a function is called it is not called in the autoload script but called in another script, example: auto.save_score() in a script of the current scene)

How and when do you save the other values to the config file? If you use another ConfigFile instance for that you will have to reload the one from the autoload, since it still only contains the values that were in the file at startup, while other scripts might already have written new values to the file.

close the config file between saving an opening it by making it a local variable.

#Autoload Script
extends Node

var highscore = 0

func load_score():
    var config_file := ConfigFile.new()
    config_file.load("user://hello.cfg")
    self.highscore = config_file.get_value("try",  "highscore", 0)

func save_score():
    var config_file := ConfigFile.new()
    config_file.set_value("try", "highscore", self.highscore)
    config_file.save("user://hello.cfg")
1 Like