Godot Version
Godot Engine v4.4.stable.official.4c311cbee
Question
How do you properly you load a PackedScene from saved game Resource file, while setting all variables inside?
I have storage chests that need saved when the game is saved, the loaded back in when loading the save file. I am using the Resource Class, under direction from [“Mercon22” - “Master Flexible Save Load in Godot: The Resource Class!”] on YouTube. The storage chests are the only thing not working.
My storage chests group is “g_storage_chest” and there are 2 in my scene to save. I have verified they save to my save file, though the loading doesn’t seem to work quite right. Per code, it appears to queue_free the storage chests in the scene, then spawn the ones from the PackedScene, that they were saved to, back into the scene. Unfortunately this isn’t happening. If I comment out the spawning code, I can tell they are not being queue_free’d, and they are not loading in with their inventory either (which is also verified to be in the save file).
SceneManager is my Resource being used to save files.
Assuming my issues are after #remove current storage chests comment.
func save() -> void:
var data = SceneManager.new()
data.player_position = player.global_position
data.level_loaded = get_tree().current_scene.scene_file_path
data.player_inventory = PlayerManager.INVENTORY_DATA.slots
var storage_chests = get_tree().get_nodes_in_group("g_storage_chest")
for g_storage_chest in storage_chests:
var storage_scene = PackedScene.new()
storage_scene.pack(g_storage_chest)
data.storage_chest_array.append(storage_scene)
ResourceSaver.save (data, "user://scene_manager.tres")
print("saved")
game_saved.emit()
func load() -> void:
var data = ResourceLoader.load ("user://scene_manager.tres") as SceneManager
LevelManager.load_new_level( data.level_loaded,"", Vector2.ZERO)
await LevelManager.level_load_started
#set player position and rewrite inventory
PlayerManager.set_player_position(data.player_position)
PlayerManager.INVENTORY_DATA.parse_save_data(data.player_inventory)
#remove current storage chests
for s in get_tree().get_nodes_in_group("g_storage_chest"):
print(s.name) #does print both storage chest names)
s.queue_free()
#load storage chests
for s in data.storage_chest_array:
var storage_chest_node = s.instantiate()
get_tree().current_scene.add_child(storage_chest_node)
await LevelManager.level_loaded
game_loaded.emit()