Change scene without lose the previous scene

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By EmanuelOzorio

I’m working in a turn-based battle RPG.
The game consist in a player that wanders in a world and init a battle when collide with an enemy.
When the player collide with an enemy the scene change to a battle scene.
When the battle finish the scene chage back to world scene.

How i persist the world scene when change to the battle scene? I mean, when the battle finish I want to bring back the world scene whit the same enemies and player in the same positions was are before the battle inits.

:bust_in_silhouette: Reply From: stevkastt

You can set the battle scene pause mode to process, so, when you change the the scene you pause the game, the first one will be paused but battle scene won’t. When battle finishes you could delete that scene or something and make the usual game play as it was before. I think you also would need to delete the enemy in the world, that one you killed in battle. You can find useful information about pausing games here

:bust_in_silhouette: Reply From: AspinBlack

I have the same issue and I solved it this way as I wanted to perserve the state of the first Scene while in the second Scene.
First Scene “Main” has a button connected to this function.

func _ConfigUnit():
	#Called to change to new Sceen
	var TheRoot = get_node("/root")  #need this as get_node will stop work once you remove your self from the Tree
	var ThisScene = get_node("/root/Main")
	GlobalGameData.PreviousScreen = ThisScene  #variable in Autoload script
	#print(ThisScene)
	#ThisScene.print_tree()
	TheRoot.remove_child(ThisScene)
	
	var NextScene = load("res://ConfigUnit.tscn")
	NextScene = NextScene.instance()
	TheRoot.add_child(NextScene)

Then in the next Scene i have button linked to this:

func _BackButton():
	var TheRoot = get_node("/root")  #need this as get_node will stop work once you remove your self from the Tree
	var ThisScene = get_node("/root/Node2D")

	TheRoot.remove_child(ThisScene)
	ThisScene.call_deferred("free")
	
	var NextScene = GlobalGameData.PreviousScreen
	TheRoot.add_child(NextScene)

I created this account only to say thank you, I was looking how to this scene change and return for days and this was the only solution that worked.

jnrd | 2020-12-04 07:12

2 Likes

You are great! Thank you for sharing this valuable code with everyone. It was exactly what I was looking for.