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")