Don't know how to use ScreenTree create_timer in Godot

Viewed 201

I tried from documentation example

func _physics_process(delta):
  yield(get_tree().create_timer(1.0), "timeout")
pass

func timeout():
  print("Working")
pass
1 Answers

In the example, the yield keyword is used to tell Godot to suspend execution until it receives an specified signal.

So, if you have code that looks like this:

print("hello")
yield(object, "signal_name")
print("world")

It will print "hello", then after object emits the signal "signal_name", it will continue and print "world".


Let us put create_timer now:

print("hello")
yield(get_tree().create_timer(1.0), "timeout")
print("world")

Understand that get_tree().create_timer(1.0) will return an object. In particular, create_timer returns a SceneTreeTimer. And we will be awaiting for this object to emit a signal called "timeout". In fact the SceneTreeTimer should emit said signal after one second (the time is specified by the 1.0 argument given to create_timer).


If you want to look a little deeper into how yield works, know that it will schedule the code as a continuation of the signal, and return. So Godot can and will execute other things in the mean time. No thread is blocked. This is similar to C# await.


Now, in your code:

func _physics_process(delta):
    yield(get_tree().create_timer(1.0), "timeout")

This will do nothing, then await one second, and afterwards do nothing.

And this is unrelated:

func timeout():
    print("Working")

I don't think that is how the example in the documentation looks like.

Related