How do I save my settings is a config file?

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

Ok, so I am trying to save settings in a config file but I am having a hard time figuring it out. I need to be able to save and load the values of a slider, a check button, and a check box. I would love if someone could show me the code to do this and explain how it works. Thank you!

:bust_in_silhouette: Reply From: godot_dev_

You can achieve what you are trying to do using Godot’s ConfigFile (see ConfigFile Documentation). For the record, here is a thread similar to your question, and this thread involves saving to files via other ways other than ConfigFile.

You must first create a ConfigFile object

 var newConfig = ConfigFile.new()
 #open the settings file
 var err = newConfig.load(SETTINGS_FILE_PATH) # SETTINGS_FILE_PATH = file path string to your settings file
 if err != OK: 
     print("opening config file failed" +str(err))
    return 

You can then save a value by using two different lookup keys (unique identifying strings) to identify the variable you are saving, a section key and a key to identify the variable. The section helps group variables together, so you could have multiple sections with the same variables. For the next example, suppose we have 2 groups of variables we wish to save, main menu and settings menu, represented by the following sections keys: "MAIN_MENU_SECTION", "SETTINGS_MENU_SECTION". Now, suppose for the purposes of your task, you identify the slider value, check button, and checkbox using "SLIDER_VALUE", "CHECK_BUTTON_CHOICE", and "CHECK_BOX" keys, respectively. Below is how you would save the values to the config file using the newConfig object:

newConfig.set_value("MAIN_MENU_SECTION","SLIDER_VALUE",0.5)
newConfig.set_value("MAIN_MENU_SECTION","CHECK_BUTTON_CHOICE",0.5)
newConfig.set_value("MAIN_MENU_SECTION","CHECK_BOX",0.5)

You would do the same for the settings menu to save its values, by replacing “MAIN_MENU_SECTION” with “SETTINGS_MENU_SECTION” in the above 3 lines of code. We must now save the changes made to the config object

newConfig.save(SETTINGS_FILE_PATH)

Example settings files content:

[MAIN_MENU_SECTION]

SLIDER_VALUE=0.5
CHECK_BUTTON_CHOICE=3
CHECK_BOX=true

Now, reading back the values would involve creating the ConfigFile object like shown at the start of this post, then, you would do the following to read the slider value from the main menu section

var sliderValue = newConfig.get_value("MAIN_MENU_SECTION","SLIDER_VALUE")