DreamBall/save_files.gd

48 lines
1.5 KiB
GDScript3
Raw Normal View History

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)
write(JSON.stringify({}), save_file_name)
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
func write(json_string: String, save_file_name: String) -> void:
var save_file := FileAccess.open(save_file_name, FileAccess.WRITE)
save_file.store_line(json_string)
save_file.store_line("FOR YOUR SAFETY, ALWAYS CHECK IF THE DATA OF THE FILES YOU DOWNLOAD LOOKS OKAY")
func change_property(property: String, value, save_file_name: String) -> void:
ensure_existence(save_file_name)
var data = read(save_file_name)
data[property] = value
write(JSON.stringify(data), save_file_name)