global.gd 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. extends Node
  2. # Changing scenes is most easily done using the functions `change_scene`
  3. # and `change_scene_to` of the SceneTree. This script demonstrates how to
  4. # change scenes without those helpers.
  5. func goto_scene(path):
  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. call_deferred("_deferred_goto_scene", path)
  14. func _deferred_goto_scene(path):
  15. # Immediately free the current scene, there is no risk here.
  16. get_tree().get_current_scene().free()
  17. # Load new scene
  18. var packed_scene = ResourceLoader.load(path)
  19. # Instance the new scene
  20. var instanced_scene = packed_scene.instance()
  21. # Add it to the scene tree, as direct child of root
  22. get_tree().get_root().add_child(instanced_scene)
  23. # Set it as the current scene, only after it has been added to the tree
  24. get_tree().set_current_scene(instanced_scene)