How to save data

Godot Version

4.2.2 stable

Question

I am trying to make code to create a world and save the data, but it doesn’t create anything and prints out an error (that I placed). Can anybody help me?

Heres the code:

func save_world():
var saved_worlds = list_saved_worlds()

if saved_worlds.size() >= 10:
	print("Maximum number of saved worlds reached. Cannot save more.")
	return
var use_space = true
var timedict = Time.get_datetime_dict_from_system(use_space)
var time = Time.get_datetime_string_from_datetime_dict(timedict,use_space)
var file_path = "user://Saves/world_" + time + ".MW"
print("Saving world to file:", file_path)


var file = FileAccess.open(file_path, FileAccess.WRITE)
if !file:
	print("Error opening file for saving")
	return



for block in get_children():
	if block is StaticBody3D:
		file.store_var(block.transform.origin)
		print("Saved block at position:", block.transform.origin)

file.close()
print("World saved successfully at ", file_path)

Looks like you can use FileAccess.get_open_error() to get more info about the error if open() returns null. My initial thought is that maybe the “Saves” folder doesn’t exist yet and so it’s unable to create a file in there?

I have a function to make sure the saves folder exists. Also I tried to use the function and it gave me 12

12 looks like a general “can’t open” error.

Another possibility: get_datetime_string_from_datetime_dict() includes a “:” in its path, which isn’t a valid character for filenames in most operating systems. That might be why it’s refusing to create that file.

Thanks

1 Like