Trouble Saving Data

Godot Version

Godot4

Question

i was following this 2:00 tutorial, and my code looks like this:

var savePath = "user://gameData.save"
var saveTest = "testt"

func _save():
	var file = FileAccess.open(savePath, FileAccess.WRITE)
	file.store_var(saveTest)

func _load():
	if FileAccess.file_exists(savePath):
		var file = FileAccess.open(savePath, FileAccess.READ)
		print(file.get_var(saveTest))

but it only lets me save true or false as far as I’ve tested it.

What do you mean? The get_var method returns a value, the argument is controlling if you can store objects, see the documentation, that tutorial is wrong, they don’t know how to use these methods

im still confused. do you know any other way to just write and read files? i checked the documentation but it still didnt help much. im still fairly new to godot

Just use:

var savePath = "user://gameData.save"
var saveTest = "testt"

func _save():
	var file = FileAccess.open(savePath, FileAccess.WRITE)
	file.store_var(saveTest)

func _load():
	if FileAccess.file_exists(savePath):
		var file = FileAccess.open(savePath, FileAccess.READ)
		print(file.get_var())

It works fine

1 Like

thankyou this worked. how would i store multiple vars though. would that be possible? and is it good practice?

Just store them one by one, remember their order, or use a Dictionary, like so:

var data = { "key1": data1, "key2": data2 }

thanks. have a great day :grin:

1 Like

You too!

You can store as many vars as you want. Check out this video for inspiration.

1 Like
var savePath = "user://gameData.save"
var saveTest = "testt"

func _save():
	var file = FileAccess.open(savePath, FileAccess.WRITE)
	file.store_var(saveTest)
	file.store_var("tt")

func _load():
	if FileAccess.file_exists(savePath):
		var file = FileAccess.open(savePath, FileAccess.READ)
		print(file.get_var())
		print(file.get_var())

this returns:
test
tt

so i geuss you gotta access them in order and assign them vars. thanks everyone for your help. :grin:

is there a way to delete the save file?

just figured out i want to erase the data in the file but keep the file. how would i do that?

You can just open it for writing and save it empty, opening it truncates it

1 Like

thnx this worked. :smile:

1 Like