Timers in GDScript
Our first example demonstrates how to use timers in GDScript. Timers are useful when you want to execute code at some point in the future or repeatedly at some interval.
To run this script, attach it to a Node in your Godot scene. When you run the scene:
The first timer will fire approximately 2 seconds after we start the program, but the second should be stopped before it has a chance to fire.
In GDScript, we use the built-in Timer
node to create timers. We can set the wait time, whether the timer should repeat or fire only once (one-shot), and connect to its “timeout” signal to execute code when the timer fires.
Unlike in some other languages, GDScript doesn’t have built-in channels for communication between timers and the main thread. Instead, we use signals and callbacks to handle timer events.
The yield
function in GDScript can be used for simple delays, similar to time.Sleep
in some other languages. However, using Timer nodes gives us more control and allows us to stop the timer if needed.
Remember that in Godot, all nodes (including Timers) need to be added to the scene tree with add_child()
to function properly.