Tickers in GDScript
In GDScript, we can use the Timer
node to achieve similar functionality to tickers. Here’s an example of how to create a ticker that ticks periodically until we stop it.
extends Node
var timer: Timer
var tick_count = 0
func _ready():
# Create a new Timer node
timer = Timer.new()
add_child(timer)
# Set the timer to tick every 500 milliseconds
timer.set_wait_time(0.5)
timer.set_one_shot(false)
# Connect the timeout signal to our tick function
timer.connect("timeout", self, "_on_Timer_timeout")
# Start the timer
timer.start()
# Stop the timer after 1.6 seconds
yield(get_tree().create_timer(1.6), "timeout")
timer.stop()
print("Timer stopped")
func _on_Timer_timeout():
tick_count += 1
print("Tick at ", OS.get_datetime())
# Stop after 3 ticks
if tick_count >= 3:
timer.stop()
print("Timer stopped")
In this GDScript example, we’re using a Timer
node to create a ticker-like behavior. Here’s how it works:
We create a new
Timer
node in the_ready()
function, which is called when the script is initialized.We set the timer to tick every 500 milliseconds (0.5 seconds) using
set_wait_time(0.5)
.We set the timer to repeat by calling
set_one_shot(false)
.We connect the timer’s “timeout” signal to our
_on_Timer_timeout()
function, which will be called every time the timer ticks.We start the timer with
timer.start()
.We use
yield(get_tree().create_timer(1.6), "timeout")
to wait for 1.6 seconds before stopping the timer.In the
_on_Timer_timeout()
function, we print the current time for each tick and increment a counter.After 3 ticks, we stop the timer.
When we run this program, the timer should tick 3 times before we stop it. The output might look something like this:
Tick at {year:2023, month:6, day:15, weekday:4, hour:10, minute:30, second:0}
Tick at {year:2023, month:6, day:15, weekday:4, hour:10, minute:30, second:0}
Tick at {year:2023, month:6, day:15, weekday:4, hour:10, minute:31, second:1}
Timer stopped
Note that in GDScript, we don’t have built-in concurrency primitives like goroutines or channels. Instead, we typically use signals and the scene tree to manage asynchronous operations. The yield
function provides a way to pause execution and resume it later, which can be used for simple coroutine-like behavior.