42 lines
966 B
GDScript
42 lines
966 B
GDScript
extends Node
|
|
|
|
const SAVE_PATH: String = "user://savegame.json"
|
|
|
|
var save_data: Dictionary = {}
|
|
var is_loaded: bool = false
|
|
|
|
func _ready() -> void:
|
|
load_game()
|
|
|
|
func save_game() -> void:
|
|
var save_file = FileAccess.open(SAVE_PATH, FileAccess.WRITE)
|
|
var save_nodes = get_tree().get_nodes_in_group("Saveable")
|
|
var new_save_data: Dictionary = {}
|
|
|
|
for node in save_nodes:
|
|
if not node.has_method("get_save_data"):
|
|
continue
|
|
|
|
var node_data = node.get_save_data()
|
|
var node_path = str(node.get_path())
|
|
new_save_data[node_path] = node_data
|
|
|
|
var json_string = JSON.stringify(new_save_data)
|
|
save_file.store_line(json_string)
|
|
|
|
func load_game() -> void:
|
|
if not FileAccess.file_exists(SAVE_PATH):
|
|
is_loaded = true
|
|
return
|
|
|
|
var file = FileAccess.open(SAVE_PATH, FileAccess.READ)
|
|
var json_string = file.get_as_text()
|
|
|
|
var json = JSON.new()
|
|
var parse_result = json.parse(json_string)
|
|
|
|
if parse_result == OK:
|
|
save_data = json.data
|
|
|
|
is_loaded = true
|