How can I pause execution for a certain amount of time in Godot? I can't really find a clear answer.
The equivalent of Thread.Sleep(1000);
for Godot is OS.DelayMsec(1000)
. The documentation says:
Delays execution of the current thread by
msec
milliseconds.msec
must be greater than or equal to0
. Otherwise, delay_msec will do nothing and will print an error message.Note: delay_msec is a blocking way to delay code execution. To delay code execution in a non-blocking way, see SceneTree.create_timer. Yielding with SceneTree.create_timer will delay the execution of code placed below the
yield
without affecting the rest of the project (or editor, for EditorPlugins and EditorScripts).Note: When delay_msec is called on the main thread, it will freeze the project and will prevent it from redrawing and registering input until the delay has passed. When using delay_msec as part of an EditorPlugin or EditorScript, it will freeze the editor but won't freeze the project if it is currently running (since the project is an independent child process).
The same one-liner but for Godot 4.0 would be:
await get_tree().create_timer(1).timeout
The equivalent of Thread.Sleep(1000);
for Godot is OS.DelayMsec(1000)
. The documentation says:
Delays execution of the current thread by
msec
milliseconds.msec
must be greater than or equal to0
. Otherwise, delay_msec will do nothing and will print an error message.Note: delay_msec is a blocking way to delay code execution. To delay code execution in a non-blocking way, see SceneTree.create_timer. Yielding with SceneTree.create_timer will delay the execution of code placed below the
yield
without affecting the rest of the project (or editor, for EditorPlugins and EditorScripts).Note: When delay_msec is called on the main thread, it will freeze the project and will prevent it from redrawing and registering input until the delay has passed. When using delay_msec as part of an EditorPlugin or EditorScript, it will freeze the editor but won't freeze the project if it is currently running (since the project is an independent child process).
One-liner:
yield(get_tree().create_timer(1), "timeout")
This will delay the execution of the following line for 1 second.
Usually I make this to a sleep()
function for convenience:
func sleep(sec):
yield(get_tree().create_timer(sec), "timeout")
Call it with sleep(1)
to delay 1 second.
Godot 4 what worked for me was:
await get_tree().create_timer(1).timeout
I see different answers but an important aspect is not mentioned: would you like to have the thread blocked or waiting?
see related wiki page
Blocking way:
Thread.Sleep(1000);
Non-blocking:
await get_tree().create_timer(1).timeout
© 2022 - 2024 — McMap. All rights reserved.