DreamBall/save_files.gd

38 lines
1.2 KiB
GDScript

extends Node
const names := [
"user://save_file_1.save",
"user://save_file_2.save",
"user://save_file_3.save",
]
var selected_file := names[0]
func _ready() -> void:
for save_file_name in names:
ensure_existence(save_file_name)
func ensure_existence(save_file_name: String) -> void:
if save_file_name in names and not FileAccess.file_exists(save_file_name):
print("Save file ", save_file_name, " not found, creating it")
empty(save_file_name)
func empty(save_file_name: String) -> void:
print("Writing an empty object on ", save_file_name)
var save_file := FileAccess.open(save_file_name, FileAccess.WRITE)
save_file.store_line(JSON.stringify({}))
save_file.store_line("FOR YOUR SAFETY, ALWAYS CHECK IF THE DATA OF THE FILES YOU DOWNLOAD LOOKS OKAY")
func read(save_file_name: String) -> Variant:
ensure_existence(save_file_name)
selected_file = save_file_name
var save_file := FileAccess.open(save_file_name, FileAccess.READ)
var json := JSON.new()
var json_string := save_file.get_line()
if json.parse(json_string) != OK:
print("(SAVES) JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
return {}
return json.data