Why is my code not saving please help!

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

Saving the “First_timer” variable works but not any other please tell me why???

func save_data():
	var file = FileAccess.open(save_path, FileAccess.WRITE)
	file.store_var(first_timer)
	file.store_float(float(weight))
	file.store_float(float(heightf))
	file.store_float(float(height))

func load_score():
	if FileAccess.file_exists(save_path):
		print("file found")
		var file = FileAccess.open(save_path, FileAccess.READ)
		first_timer = file.get_var()
		height = file.get_var()
		weight = file.get_var()
		heightf= file.get_float()
	else:
		print("file not found")
		first_timer = true
		weight = 0
		height = 0
		heightf = 0
:bust_in_silhouette: Reply From: Enfyna
var save  : Dictionary

func save_game():
    var json = JSON.stringify(save,"\t")
    var file = FileAccess.open(save_path, FileAccess.WRITE)
    file.store_string(json)
    print_debug("Game saved.")#Save data : "+str(json))
    return

func load_save():
    # If no save file create new one
    if not FileAccess.file_exists(save_path):
	    var file = FileAccess.open(save_path, FileAccess.WRITE)
	    var json = JSON.stringify(save,"\t")
	    file.store_string(json)
	    print_debug("Created new save file.")#Save data : "+str(json))
	    return
    # Save file found 
    var file = FileAccess.open(save_path, FileAccess.READ)
    var json = file.get_as_text()
    var data = JSON.parse_string(json)
    self.save = data
    print_debug("Game loaded.")
    #print_debug("data :  "+str(data))
    return

You should learn saving with JSON i think. For example this is a code I use in my game. I put this code in my autoloaded Global script . If you used this code your save variable would look like :

var save : Dictionary = {
    "first_timer":false,
    "weight":0,
    "height":0,
    }

when you are doing:

func save_data():
var file = FileAccess.open(save_path, FileAccess.WRITE)
file.store_var(first_timer)
file.store_float(float(weight))
file.store_float(float(heightf))
file.store_float(float(height))

you are overwriting the file’s contents with file.store_var(first_timer)
then again with file.store_float(float(weight))
and again and again. so it will only actually contain the last value

you should consider writing the values to a dictionary and then storing the dictionary in the file and make the file a .json format otherwise you could store the values in an array and save the array to the file. but using a .json would work much better and they return data in a godot variable so you can immidiately work with them as variables without having to convert them from strings to variables

Cyber-Kun | 2023-04-02 16:00

You should’ve post this as a answer.

Enfyna | 2023-04-02 19:33