How do we wait for the change_scene function to get finish?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Naufan Rusyda Faikar

I’ve a simple code just like this:

func start_game() -> void:
   goto_scene("res://game/Adventure.tscn")
   print("Hello")
func goto_scene(path) -> void:
    get_tree().change_scene(path)
    print("Guys!")

it prints:

Guys!
Hello

But I want it prints:

Hello
Guys!

I’ve read Godot documentation about yield and coroutines, but get stuck in the implementation.

Thanks! Any help wil be apreciated!

Couldn’t you just swap where those two print functions are being called?

SIsilicon | 2018-12-25 13:52

:bust_in_silhouette: Reply From: omggomb

You call goto_scene first, that’s why it prints “Guys” first, because the whole method finishes before it does the next thing (print(“Hello”)). change_scene is a blocking call, it won’t do anything you can wait for, instead it will block your whole game until it’s finished, so it is like this (callstack):

  1. start_game
  2. goto_scene
  3. change_scene
  4. print(“Guys”) # This is wheregoto_scene ends and returns to start_game
  5. print(“Hello”)

If you actually want to change the scene asynchronously you’ll need to use a thread, see the docs on that:
Docs on background loading

Potentially misleading, change_scene is NOT blocking. It is a deferred call.
https://github.com/godotengine/godot/blob/e2b66cacf78ae39b94df748e9740b98a1f011e77/scene/main/scene_tree.cpp#L1310

dirtsea | 2020-08-10 07:18