global.gd 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. extends Node
  2. # Changing scenes is most easily done using the functions change_scene_to_file
  3. # and change_scene_to_packed of the SceneTree. This script demonstrates how to
  4. # change scenes without those helpers.
  5. func goto_scene(path: String):
  6. # This function will usually be called from a signal callback,
  7. # or some other function from the running scene.
  8. # Deleting the current scene at this point might be
  9. # a bad idea, because it may be inside of a callback or function of it.
  10. # The worst case will be a crash or unexpected behavior.
  11. # The way around this is deferring the load to a later time, when
  12. # it is ensured that no code from the current scene is running:
  13. _deferred_goto_scene.call_deferred(path)
  14. func _deferred_goto_scene(path: String):
  15. # Immediately free the current scene. There is no risk here because the
  16. # call to this method is already deferred.
  17. get_tree().current_scene.free()
  18. var packed_scene := ResourceLoader.load(path) as PackedScene
  19. var instanced_scene := packed_scene.instantiate()
  20. # Add it to the scene tree, as direct child of root
  21. get_tree().root.add_child(instanced_scene)
  22. # Set it as the current scene, only after it has been added to the tree
  23. get_tree().current_scene = instanced_scene