monsterfangen/resources/save_game/save_manager.gd

69 lines
2 KiB
GDScript

extends Node
# The group of nodes to save is named "save_nodes"
# Reference to the currently loaded save game
@onready var current_save : SavedGame = SavedGame.new()
var world: Node3D
func save_game() -> void:
# Create a new empty save game
var saved_game: SavedGame = SavedGame.new()
# Save the environment data
saved_game.world = SceneManager.get_world()
saved_game.daytime = 12.5
saved_game.weather = "this should be an enum"
# Save the party data
for monster: MonsterData in SaveManager.current_save.party:
saved_game.party.append(monster)
# Create an array to store the data of all other nodes
var saved_data : Array[SavedData] = []
# Use a group call to collect all the data from the other objects
get_tree().call_group("save_nodes", "on_save_game", saved_data)
# Store the array in the saved game
saved_game.saved_data = saved_data
# Store it into a file
ResourceSaver.save(saved_game, "user://savegame.tres")
func load_game() -> void:
# Load the saved game file
var saved_game : SavedGame = load("user://savegame.tres") as SavedGame
# Return if no save file is found
if saved_game == null:
print("No savegame found.")
return
# Save a reference to the current save game
current_save = saved_game
# Clean up all non-static objects from the scene
get_tree().call_group("save_nodes", "on_before_load_game")
# Restore world data
SceneManager.set_world(saved_game.world)
# Restore all other nodes
for node: SavedData in saved_game.saved_data:
# Instantiate the scene for the node
var scene: PackedScene = load(node.scene_path) as PackedScene
var restored_node: Node = scene.instantiate()
# Add the item to the world
# todo: add parent as value to save and restore to the parent
SceneManager.current_world.add_child(restored_node)
# run a callback to restore the item's state
if restored_node.has_method("on_load_game"):
restored_node.on_load_game(node)
func save_exists() -> bool:
return FileAccess.file_exists("user://savegame.tres")