Channels in GDScript

In GDScript, we can use signals to achieve similar functionality to channels. Signals allow different parts of your code to communicate asynchronously.

extends Node

signal message_sent(content)

func _ready():
    # Connect the signal to the receiving function
    connect("message_sent", self, "_on_message_received")
    
    # Send a message asynchronously
    call_deferred("_send_message")

func _send_message():
    # Emit the signal with the message
    emit_signal("message_sent", "ping")

func _on_message_received(content):
    # Receive and print the message
    print(content)

In this example, we’re using GDScript’s signal system to mimic the behavior of channels:

  1. We define a signal message_sent that can carry a payload (in this case, a string).

  2. In the _ready() function, we connect the signal to a receiving function _on_message_received.

  3. We use call_deferred to schedule the _send_message function to be called on the next frame, simulating the asynchronous nature of goroutines.

  4. In _send_message, we emit the signal with the message “ping”.

  5. The _on_message_received function acts as the receiver, printing out the received message.

When we run this script, the “ping” message is successfully passed from one part of the code to another via our signal.

$ godot -s my_script.gd
ping

By default, signals in GDScript are emitted and received asynchronously, which allows for a similar flow control to channels in other languages. This property allows us to send and receive messages between different parts of our code without needing to use additional synchronization mechanisms.

While signals in GDScript don’t provide the same level of concurrency control as channels in some other languages, they serve as a powerful tool for decoupled, event-driven programming in Godot game development.