Improvements to the save system

Godot Version

4.3

Question

I wrote a system for saving game data (written in a global script) Can this code be improved in any way? And is there any need to improve or is everything good here?

Code:

extends Node

func  _ready() -> void:
	var timer = Timer.new()
	timer.wait_time = 5
	timer.connect("timeout", Callable(self, "_on_timeout"))
	add_child(timer)
	timer.start()
	load_game()


func _on_timeout():
	save_game()

func save():
	var save_dict = {
		"gold_coin" : Globals.upgrade_coin,
		"level_locked" : Globals.unlockedLevels
	}
	return save_dict
	
func save_game():
	var save_file = FileAccess.open_encrypted_with_pass("user://savegame.save", FileAccess.WRITE, "D")
	var json_string = JSON.stringify(save())
	save_file.store_line(json_string)

func load_game():
	if not FileAccess.file_exists("user://savegame.save"):
		return
	
	var save_file = FileAccess.open_encrypted_with_pass("user://savegame.save", FileAccess.READ, "D")
	var json_string = save_file.get_as_text()
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	
	if parse_result == OK:
		var save_dict = json.get_data()
		Globals.upgrade_coin = save_dict.get("gold_coin", 0)
		Globals.unlockedLevels = save_dict.get("level_locked", 0)
	else:
		print("Error parsing save game data")

If you don’t want to manually edit the content of save files in a text editor, you can directly save and load the Dictionary to avoid JSON operations. Instead of using store_line, you’ll use store_var. That’s how we do it in our game.

2 Likes

Thanks for the advice

I use [ResourceLoader] and [ResourceSaver] to save game data.

class SaveData: public Resource{
 Dicitonary data;
}


[gdscript]
var data = SaveData.new()
ResourceSaver.save(data,"user://path.tres")

SaveData data = ResourceLoader.load("user://path.tres")
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.