Range Over Channels in GDScript
In a previous example, we saw how for
loops provide iteration over basic data structures. In GDScript, we can use a similar syntax to iterate over values received from a signal.
extends Node
signal queue(value: String)
func _ready():
# We'll emit 2 values through the 'queue' signal.
call_deferred("emit_signal", "queue", "one")
call_deferred("emit_signal", "queue", "two")
# Connect the signal to a method that will handle the emitted values
connect("queue", self, "_on_queue_value")
func _on_queue_value(value: String):
print(value)
This example demonstrates how to use signals in GDScript, which are similar to channels in other languages. We’re emitting two values through the queue
signal.
The connect
method is used to associate the queue
signal with the _on_queue_value
method. This method will be called each time a value is emitted through the signal.
To run this script:
- Create a new script in Godot and paste the code above.
- Attach the script to a Node in your scene.
- Run the scene.
You should see the following output:
one
two
This example shows how signals can be used to pass values between different parts of your GDScript code, similar to how channels are used in other languages. However, unlike channels, signals in GDScript don’t have a built-in way to be “closed”. If you need to stop listening to a signal, you would typically use the disconnect
method.