From a3aefa4eee3c2b185b31ccff5abbc60dec8ad950 Mon Sep 17 00:00:00 2001 From: Juan Linietsky Date: Sun, 12 Apr 2015 20:57:26 -0300 Subject: [PATCH] scene switcher demo changed to reflect tutorial, fixes #1673 --- misc/autoload/global.gd | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/misc/autoload/global.gd b/misc/autoload/global.gd index a0415c6e..5d81f9e6 100644 --- a/misc/autoload/global.gd +++ b/misc/autoload/global.gd @@ -3,21 +3,39 @@ extends Node var current_scene = null +func _deferred_goto_scene(path): -func goto_scene(scene): - #load new scene - var s = ResourceLoader.load(scene) - #queue erasing old (don't use free because that scene is calling this method) - current_scene.queue_free() - #instance the new scene + # Immediately free the current scene, + # there is no risk here. + current_scene.free() + + # Load new scene + var s = ResourceLoader.load(path) + + # Instance the new scene current_scene = s.instance() - #add it to the active scene, as child of root + + # Add it to the active scene, as child of root get_tree().get_root().add_child(current_scene) +func goto_scene(path): + + # This function will usually be called from a signal callback, + # or some other function from the running scene. + # Deleting the current scene at this point might be + # a bad idea, because it may be inside of a callback or function of it. + # The worst case will be a crash or unexpected behavior. + + # The way around this is deferring the load to a later time, when + # it is ensured that no code from the current scene is running: + + call_deferred("_deferred_goto_scene",path) + func _ready(): - # get the current scene + # Get the current scene, the first time. # it is always the last child of root, - # after the autoloaded nodes + # after the autoloaded nodes. + var root = get_tree().get_root() current_scene = root.get_child( root.get_child_count() -1 )