Godot saving state between scenes when switching

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Derek
:warning: Old Version Published before Godot 3 was released.

Hey folks,

I want to switch between two scenes based on their paths. At the moment I have a global that handles the switching, as so:

extends Node

var current_scene_path = null
var scenes = {}

func _ready():
	# Fetch the current scene and add it to the scenes dictionary
	var current_scene = get_tree().get_current_scene()
	current_scene_path = current_scene.get_path()
	scenes[current_scene_path] = current_scene

func change_scene(path):
	call_deferred("_change_scene", path)

func _change_scene(path):
	if current_scene_path == path:
		# Can't switch to the scene we are currently in
		return

	if not path in scenes:
		# If path is not scenes then load the scene from disk and then switch to it
		var s = ResourceLoader.load(path)
		var scene = s.instance()
		scenes[path] = scene
		return _change_scene(path)

	# Remove the current scene from the scene tree
	get_tree().get_root().remove_child(scenes[current_scene_path])

	# Load the already loaded scene from the scenes dictionary
	var scene = scenes[path]
	current_scene_path = path
	get_tree().get_root().add_child(scene)
	get_tree().set_current_scene(scene)
	return

However the problem lies in the ready function. It tries to fetch the path of the current scene, which ends up being /root/game and not res//whatever which is what change_scene is expecting, thus if change scene is called with the original starting scene it will load a new scene instead of using the existing one.

Please can you suggest how to get the resource path of the current scene or another workaround to my problem, thank you!

:bust_in_silhouette: Reply From: volzhs

Here is what document in editor says.

* NodePath get_path() const

Return the absolute path of the current node. This only works if the current node is inside the scene tree (see is_inside_tree()).
* String get_filename() const
Return a filename that may be contained by the node. When a scene is instanced from a file, it topmost node contains the filename from where it was loaded (see set_filename()).

Based on this information, you should use get_filename() instead of get_path() in your case.