global.gd 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. extends Node
  2. # Changing scenes is most easily done using the `change_scene_to_file()` and
  3. # `change_scene_to_packed()` methods of SceneTree. This script demonstrates
  4. # how to change scenes without those helpers.
  5. func goto_scene(path: String) -> void:
  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) -> void:
  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: PackedScene = ResourceLoader.load(path)
  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