Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

Signal

代表 Object 中某個訊號的內建型別。

說明

Signal is a built-in Variant type that represents a signal of an Object instance. Like all Variant types, it can be stored in variables and passed to functions. Signals allow all connected Callables (and by extension their respective objects) to listen and react to events, without directly referencing one another. This keeps the code flexible and easier to manage. You can check whether an Object has a given signal name using Object.has_signal().

In GDScript, signals can be declared with the signal keyword. In C#, you may use the [Signal] attribute on a delegate.

signal attacked

# Additional arguments may be declared.
# These arguments must be passed when the signal is emitted.
signal item_dropped(item_name, amount)

Connecting signals is one of the most common operations in Godot and the API gives many options to do so, which are described further down. The code block below shows the recommended approach.

func _ready():
    var button = Button.new()
    # `button_down` here is a Signal Variant type. We therefore call the Signal.connect() method, not Object.connect().
    # See discussion below for a more in-depth overview of the API.
    button.button_down.connect(_on_button_down)

    # This assumes that a `Player` class exists, which defines a `hit` signal.
    var player = Player.new()
    # We use Signal.connect() again, and we also use the Callable.bind() method,
    # which returns a new Callable with the parameter binds.
    player.hit.connect(_on_player_hit.bind("sword", 100))

func _on_button_down():
    print("Button down!")

func _on_player_hit(weapon_type, damage):
    print("Hit with weapon %s for %d damage." % [weapon_type, damage])

Object.connect() or Signal.connect()?

As seen above, the recommended method to connect signals is not Object.connect(). The code block below shows the four options for connecting signals, using either this legacy method or the recommended connect(), and using either an implicit Callable or a manually defined one.

func _ready():
    var button = Button.new()
    # Option 1: Object.connect() with an implicit Callable for the defined function.
    button.connect("button_down", _on_button_down)
    # Option 2: Object.connect() with a constructed Callable using a target object and method name.
    button.connect("button_down", Callable(self, "_on_button_down"))
    # Option 3: Signal.connect() with an implicit Callable for the defined function.
    button.button_down.connect(_on_button_down)
    # Option 4: Signal.connect() with a constructed Callable using a target object and method name.
    button.button_down.connect(Callable(self, "_on_button_down"))

func _on_button_down():
    print("Button down!")

While all options have the same outcome (button's BaseButton.button_down signal will be connected to _on_button_down), option 3 offers the best validation: it will print a compile-time error if either the button_down Signal or the _on_button_down Callable are not defined. On the other hand, option 2 only relies on string names and will only be able to validate either names at runtime: it will generate an error at runtime if "button_down" is not a signal, or if "_on_button_down" is not a method in the object self. The main reason for using options 1, 2, or 4 would be if you actually need to use strings (e.g. to connect signals programmatically based on strings read from a configuration file). Otherwise, option 3 is the recommended (and fastest) method.

Binding and passing parameters:

The syntax to bind parameters is through Callable.bind(), which returns a copy of the Callable with its parameters bound.

When calling emit() or Object.emit_signal(), the signal parameters can be also passed. The examples below show the relationship between these signal parameters and bound parameters.

func _ready():
    # This assumes that a `Player` class exists, which defines a `hit` signal.
    var player = Player.new()
    # Using Callable.bind().
    player.hit.connect(_on_player_hit.bind("sword", 100))

    # Parameters added when emitting the signal are passed first.
    player.hit.emit("Dark lord", 5)

# We pass two arguments when emitting (`hit_by`, `level`),
# and bind two more arguments when connecting (`weapon_type`, `damage`).
func _on_player_hit(hit_by, level, weapon_type, damage):
    print("Hit by %s (level %d) with weapon %s for %d damage." % [hit_by, level, weapon_type, damage])

Note: In a boolean context, a signal will evaluate to false if it's null (see is_null()). Otherwise, a signal will always evaluate to true.

備註

使用 C# 操作此 API 時有顯著差異,詳見 C# API 與 GDScript 的不同

教學

建構子

Signal

Signal()

Signal

Signal(from: Signal)

Signal

Signal(object: Object, signal: StringName)

方法

int

connect(callable: Callable, flags: int = 0)

void

disconnect(callable: Callable)

void

emit(...) vararg const

Array

get_connections() const

StringName

get_name() const

Object

get_object() const

int

get_object_id() const

bool

has_connections() const

bool

is_connected(callable: Callable) const

bool

is_null() const

運算子

bool

operator !=(right: Signal)

bool

operator ==(right: Signal)


建構子說明

Signal Signal() 🔗

建構空的 Signal,沒有綁定物件和訊號名稱。


Signal Signal(from: Signal)

建構給定 Signal 的副本。


Signal Signal(object: Object, signal: StringName)

Creates a Signal object referencing a signal named signal in the specified object.


方法說明

int connect(callable: Callable, flags: int = 0) 🔗

Connects this signal to the specified callable. Optional flags can be also added to configure the connection's behavior (see ConnectFlags constants). You can provide additional arguments to the connected callable by using Callable.bind().

A signal can only be connected once to the same Callable. If the signal is already connected, this method returns @GlobalScope.ERR_INVALID_PARAMETER and generates an error, unless the signal is connected with Object.CONNECT_REFERENCE_COUNTED. To prevent this, use is_connected() first to check for existing connections.

for button in $Buttons.get_children():
    button.pressed.connect(_on_pressed.bind(button))

func _on_pressed(button):
    print(button.name, " was pressed")

Note: If the callable's object is freed, the connection will be lost.


void disconnect(callable: Callable) 🔗

將該訊號與給定的 Callable 斷開連接。如果該連接不存在,則會生成錯誤。請使用 is_connected() 來確保連接存在。


void emit(...) vararg const 🔗

發出該訊號。與該訊號相連的所有 Callable 都將被觸發。此方法支援可變數量的參數,所以參數可以用逗號分隔列表的形式傳遞。


Array get_connections() const 🔗

返回該訊號的連接 Array。連接用 Dictionary 表示,包含三個條目:

  • signal 是對此訊號的引用。

  • callable 是對連接的 Callable 的引用。

  • flagsConnectFlags 的組合。


StringName get_name() const 🔗

返回該訊號的名稱。


Object get_object() const 🔗

返回發出該訊號的物件。


int get_object_id() const 🔗

返回發出該訊號的物件的 ID(見 Object.get_instance_id())。


bool has_connections() const 🔗

Returns true if any Callable is connected to this signal.


bool is_connected(callable: Callable) const 🔗

如果指定的 Callable 已連接到此訊號,則返回 true


bool is_null() const 🔗

Returns true if this Signal has no object and the signal name is empty. Equivalent to signal == Signal().


運算子說明

bool operator !=(right: Signal) 🔗

如果訊號的物件或名稱不同,則返回 true


bool operator ==(right: Signal) 🔗

如果訊號的物件和名稱相同,則返回 true