How to reload game scene with variables from save file?

Godot Version

v4.2.2.stable.official [15073afe3]

Question

I am trying to implement a save and load system for the first time in my Castlevania-style 2D action platformer. When the player saves the game, I want the game scene to reload itself, respawning non-boss enemies and player health in the process, while also retaining the information (money, subweapon, ammo, position, and bosses defeated) stored in the save variables. That way the player keeps their possessions/position and bosses don’t respawn, but everything else is reset to starting conditions.

It looks like the save part is working fine, as I have looked in the save file path and the variables are stored correctly. The problem occurs when I reload the game scene (see line commented out) and none of the information in the save file is regarded (player spawns at their initial start point with no money/subweapon/ammo, boss respawns, etc.).

So the problem seems to be with my load function. Any advice on making this work? Eventually I’d like to implement a similar load function when the player selects “Continue” from the start menu as well.

func save():
	print ("Save game function running.")
	var save_game = SaveGame.new()
	
	save_game.moneypool = moneypool
	save_game.subweapon = player.subweapon
	save_game.subpool = subpool
	save_game.save_position = player.global_position
	save_game.gratch_defeated = gratch_defeated
	
	ResourceSaver.save(save_game, save_file_path)	
	print("save")
	player.saving = false
	load_data()

func load_data():
	print("Load data function running...")
	
	#get_tree().change_scene_to_file("res://Scenes/game.tscn")
	
	var save_game:SaveGame = load(save_file_path) as SaveGame
	
	moneypool = save_game.moneypool
	player.subweapon = save_game.subweapon
	subpool = save_game.subpool
	player.global_position = save_game.save_position
	gratch_defeated = save_game.gratch_defeated
	
	print("loaded!")

I added some lines that should make the function wait for the tree, but that doesn’t really seem to work either.

func load_data():
	print("Load data function running...")
	
	get_tree().change_scene_to_file("res://Scenes/game.tscn")
	#get_tree().reload_current_scene
	
	await tree_entered
	await get_tree().process_frame
	var save_game:SaveGame = load(save_file_path) as SaveGame
	
	moneypool = save_game.moneypool
	player.subweapon = save_game.subweapon
	subpool = save_game.subpool
	player.global_position = save_game.save_position
	gratch_defeated = save_game.gratch_defeated
	
	print("loaded!")

If this Script is an Autoload then it will never re-enter the tree. If it is not an autoload then it will be exiting the tree, and a new object will enter the tree, not this one.


Try as an Autoload, await get_tree().process_frame should allow the scene change to finish and everything be ready; your player reference will need to be updated though.

1 Like