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.
Checking the stable version of the documentation...
Signal
Un type intégré représentant un signal d'un Object.
Description
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)
[Signal]
delegate void AttackedEventHandler();
// Additional arguments may be declared.
// These arguments must be passed when the signal is emitted.
[Signal]
delegate void ItemDroppedEventHandler(string itemName, int 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])
public override void _Ready()
{
var button = new Button();
// C# supports passing signals as events, so we can use this idiomatic construct:
button.ButtonDown += OnButtonDown;
// This assumes that a `Player` class exists, which defines a `Hit` signal.
var player = new Player();
// We can use lambdas when we need to bind additional parameters.
player.Hit += () => OnPlayerHit("sword", 100);
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
private void OnPlayerHit(string weaponType, int damage)
{
GD.Print($"Hit with weapon {weaponType} for {damage} 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!")
public override void _Ready()
{
var button = new Button();
// Option 1: In C#, we can use signals as events and connect with this idiomatic syntax:
button.ButtonDown += OnButtonDown;
// Option 2: GodotObject.Connect() with a constructed Callable from a method group.
button.Connect(Button.SignalName.ButtonDown, Callable.From(OnButtonDown));
// Option 3: GodotObject.Connect() with a constructed Callable using a target object and method name.
button.Connect(Button.SignalName.ButtonDown, new Callable(this, MethodName.OnButtonDown));
}
private void OnButtonDown()
{
GD.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])
public override void _Ready()
{
// This assumes that a `Player` class exists, which defines a `Hit` signal.
var player = new Player();
// Using lambda expressions that create a closure that captures the additional parameters.
// The lambda only receives the parameters defined by the signal's delegate.
player.Hit += (hitBy, level) => OnPlayerHit(hitBy, level, "sword", 100);
// Parameters added when emitting the signal are passed first.
player.EmitSignal(SignalName.Hit, "Dark lord", 5);
}
// We pass two arguments when emitting (`hit_by`, `level`),
// and bind two more arguments when connecting (`weapon_type`, `damage`).
private void OnPlayerHit(string hitBy, int level, string weaponType, int damage)
{
GD.Print($"Hit by {hitBy} (level {level}) with weapon {weaponType} for {damage} 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.
Note
Il y a des différences notables dans l'utilisation de cette API en C#. Voir Différences de l'API C# par rapport à GDScript pour plus d'informations.
Tutoriels
Constructeurs
Signal() |
|
Signal(object: Object, signal: StringName) |
Méthodes
void |
disconnect(callable: Callable) |
void |
emit(...) vararg const |
get_connections() const |
|
get_name() const |
|
get_object() const |
|
get_object_id() const |
|
has_connections() const |
|
is_connected(callable: Callable) const |
|
is_null() const |
Opérateurs
operator !=(right: Signal) |
|
operator ==(right: Signal) |
Descriptions des constructeurs
Construit un Signal vide sans objet ni nom de signal lié.
Construit un Signal comme une copie du Signal donné.
Signal Signal(object: Object, signal: StringName)
Crée un objet Signal faisant référence à un signal nommé signal dans l'objet object spécifié.
Descriptions des méthodes
int connect(callable: Callable, flags: int = 0) 🔗
Connecte ce signal au callable spécifié. Des drapeaux flags optionnels peuvent aussi être ajoutés pour configurer le comportement de la connexion (voir les constantes ConnectFlags). Vous pouvez fournir des arguments supplémentaires au callable connecté en utilisant Callable.bind().
Un signal ne peut être connecté qu'une fois au même Callable. Si le signal est déjà connecté, cette méthode renvoie @GlobalScope.ERR_INVALID_PARAMETER et génère une erreur, à moins que le signal ne soit connecté à Object.CONNECT_REFERENCE_COUNTED. Pour éviter cela, utilisez d'abord is_connected() pour vérifier les connexions existantes.
for bouton in $Buttons.get_children():
bouton.pressed.connect(_lorsque_appuye.bind(button))
func _lorsque_appuye(button):
print(bouton.name, " a été appuyé")
Note : Si l'objet callable est libéré, la connexion sera perdue.
void disconnect(callable: Callable) 🔗
Déconnecte ce signal du Callable spécifié. Si la connexion n'existe pas, génère une erreur. Utilisez is_connected() pour vous assurer que la connexion existe.
void emit(...) vararg const 🔗
Émet ce signal. Tous les Callable connectés à ce signal seront déclenchés. Cette méthode prend en charge un nombre variable d'arguments, de sorte à ce que les paramètres peuvent être passés en tant que liste séparée par des virgules.
Array get_connections() const 🔗
Renvoie un Array des connexions pour ce signal. Chaque connexion est représentée comme un Dictionary qui contient trois entrées :
signalest une référence à ce signal,callableest une référence au Callable connecté,flagsest une combinaison de drapeaux ConnectFlags.
StringName get_name() const 🔗
Renvoie le nom de ce signal.
Renvoie l'objet émettant ce signal.
Renvoie l'ID de l'objet émettant ce signal (voir Object.get_instance_id()).
bool has_connections() const 🔗
Renvoie true si au moins un Callable est connecté à ce signal.
bool is_connected(callable: Callable) const 🔗
Renvoie true si le Callable spécifié est connecté à ce signal.
Renvoie true si ce Signal n'a pas d'objet et que le nom du signal est vide. Équivalent à signal == Signal().
Descriptions des opérateurs
bool operator !=(right: Signal) 🔗
Renvoie true si les signaux ne partagent pas le même objet ou le même nom.
bool operator ==(right: Signal) 🔗
Renvoie true si les deux signaux partagent le même objet et le même nom.