Merge pull request #43245 from HaSa1002/docs-object

Docs: Object: Use new signal syntax and port to C#
This commit is contained in:
Rémi Verschelde 2021-02-08 12:53:44 +01:00 committed by GitHub
commit e2a80a4be3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -10,11 +10,20 @@
Some classes that extend Object add memory management. This is the case of [Reference], which counts references and deletes itself automatically when no longer referenced. [Node], another fundamental type, deletes all its children when freed from memory.
Objects export properties, which are mainly useful for storage and editing, but not really so much in programming. Properties are exported in [method _get_property_list] and handled in [method _get] and [method _set]. However, scripting languages and C++ have simpler means to export them.
Property membership can be tested directly in GDScript using [code]in[/code]:
[codeblock]
[codeblocks]
[gdscript]
var n = Node2D.new()
print("position" in n) # Prints "True".
print("other_property" in n) # Prints "False".
[/codeblock]
[/gdscript]
[csharp]
var node = new Node2D();
// C# has no direct equivalent to GDScript's `in` operator here, but we
// can achieve the same behavior by performing `Get` with a null check.
GD.Print(node.Get("position") != null); // Prints "True".
GD.Print(node.Get("other_property") != null); // Prints "False".
[/csharp]
[/codeblocks]
The [code]in[/code] operator will evaluate to [code]true[/code] as long as the key exists, even if the value is [code]null[/code].
Objects also receive notifications. Notifications are a simple way to notify the object about different events, so they can all be handled together. See [method _notification].
[b]Note:[/b] Unlike references to a [Reference], references to an Object stored in a variable can become invalid without warning. Therefore, it's recommended to use [Reference] for data classes instead of [Object].
@ -96,9 +105,16 @@
</argument>
<description>
Calls the [code]method[/code] on the object and returns the result. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
[codeblock]
call("set", "position", Vector2(42.0, 0.0))
[/codeblock]
[codeblocks]
[gdscript]
var node = Node2D.new()
node.call("set", "position", Vector2(42, 0))
[/gdscript]
[csharp]
var node = new Node2D();
node.Call("set", "position", new Vector2(42, 0));
[/csharp]
[/codeblocks]
[b]Note:[/b] In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).
</description>
</method>
@ -109,9 +125,16 @@
</argument>
<description>
Calls the [code]method[/code] on the object during idle time. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
[codeblock]
call_deferred("set", "position", Vector2(42.0, 0.0))
[/codeblock]
[codeblocks]
[gdscript]
var node = Node2D.new()
node.call_deferred("set", "position", Vector2(42, 0))
[/gdscript]
[csharp]
var node = new Node2D();
node.CallDeferred("set", "position", new Vector2(42, 0));
[/csharp]
[/codeblocks]
[b]Note:[/b] In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase).
</description>
</method>
@ -124,9 +147,16 @@
</argument>
<description>
Calls the [code]method[/code] on the object and returns the result. Contrarily to [method call], this method does not support a variable number of arguments but expects all parameters to be via a single [Array].
[codeblock]
callv("set", [ "position", Vector2(42.0, 0.0) ])
[/codeblock]
[codeblocks]
[gdscript]
var node = Node2D.new()
node.callv("set", ["position", Vector2(42, 0)])
[/gdscript]
[csharp]
var node = new Node2D();
node.Callv("set", new Godot.Collections.Array { "position", new Vector2(42, 0) });
[/csharp]
[/codeblocks]
</description>
</method>
<method name="can_translate_messages" qualifiers="const">
@ -148,23 +178,140 @@
<argument index="3" name="flags" type="int" default="0">
</argument>
<description>
[b]FIXME:[/b] The syntax changed with the addition of [Callable], this should be updated.
Connects a [code]signal[/code] to a [code]method[/code] on a [code]target[/code] object. Pass optional [code]binds[/code] to the call as an [Array] of parameters. These parameters will be passed to the method after any parameter used in the call to [method emit_signal]. Use [code]flags[/code] to set deferred or one-shot connections. See [enum ConnectFlags] constants.
A [code]signal[/code] can only be connected once to a [code]method[/code]. It will throw an error if already connected, unless the signal was connected with [constant CONNECT_REFERENCE_COUNTED]. To avoid this, first, use [method is_connected] to check for existing connections.
If the [code]target[/code] is destroyed in the game's lifecycle, the connection will be lost.
Examples:
[codeblock]
connect("pressed", self, "_on_Button_pressed") # BaseButton signal
connect("text_entered", self, "_on_LineEdit_text_entered") # LineEdit signal
connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # User-defined signal
[/codeblock]
An example of the relationship between [code]binds[/code] passed to [method connect] and parameters used when calling [method emit_signal]:
[codeblock]
connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # weapon_type and damage are passed last
emit_signal("hit", "Dark lord", 5) # "Dark lord" and 5 are passed first
func _on_Player_hit(hit_by, level, weapon_type, damage):
print("Hit by %s (lvl %d) with weapon %s for %d damage" % [hit_by, level, weapon_type, damage])
[/codeblock]
Connects a [code]signal[/code] to a [code]callable[/code]. Pass optional [code]binds[/code] to the call as an [Array] of parameters. These parameters will be passed to the [Callable]'s method after any parameter used in the call to [method emit_signal]. Use [code]flags[/code] to set deferred or one-shot connections. See [enum ConnectFlags] constants.
[b]Note:[/b] This method is the legacy implementation for connecting signals. The recommend modern approach is to use [method Signal.connect] and to use [method Callable.bind] to add and validate parameter binds. Both syntaxes are shown below.
A signal can only be connected once to a [Callable]. It will throw an error if already connected, unless the signal was connected with [constant CONNECT_REFERENCE_COUNTED]. To avoid this, first, use [method is_connected] to check for existing connections.
If the callable's target is destroyed in the game's lifecycle, the connection will be lost.
[b]Examples with recommended syntax:[/b]
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 for both GDScript and C#.
[codeblocks]
[gdscript]
func _ready():
var button = Button.new()
# `button_down` here is a Signal object, and we thus 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])
[/gdscript]
[csharp]
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();
// Signals as events (`player.Hit += OnPlayerHit;`) do not support argument binding. You have to use:
player.Hit.Connect(OnPlayerHit, new Godot.Collections.Array {"sword", 100 });
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
private void OnPlayerHit(string weaponType, int damage)
{
GD.Print(String.Format("Hit with weapon {0} for {1} damage.", weaponType, damage));
}
[/csharp]
[/codeblocks]
[b][code]Object.connect()[/code] or [code]Signal.connect()[/code]?[/b]
As seen above, the recommended method to connect signals is not [method Object.connect]. The code block below shows the four options for connecting signals, using either this legacy method or the recommended [method Signal.connect], and using either an implicit [Callable] or a manually defined one.
[codeblocks]
[gdscript]
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!")
[/gdscript]
[csharp]
public override void _Ready()
{
var button = new Button();
// Option 1: Object.Connect() with an implicit Callable for the defined function.
button.Connect("button_down", OnButtonDown);
// Option 2: Object.connect() with a constructed Callable using a target object and method name.
button.Connect("button_down", new Callable(self, nameof(OnButtonDown)));
// Option 3: Signal.connect() with an implicit Callable for the defined function.
button.ButtonDown.Connect(OnButtonDown);
// Option 3b: In C#, we can use signals as events and connect with this more idiomatic syntax:
button.ButtonDown += OnButtonDown;
// Option 4: Signal.connect() with a constructed Callable using a target object and method name.
button.ButtonDown.Connect(new Callable(self, nameof(OnButtonDown)));
}
private void OnButtonDown()
{
GD.Print("Button down!");
}
[/csharp]
[/codeblocks]
While all options have the same outcome ([code]button[/code]'s [signal BaseButton.button_down] signal will be connected to [code]_on_button_down[/code]), option 3 offers the best validation: it will throw a compile-time error if either the [code]button_down[/code] signal or the [code]_on_button_down[/code] callable are undefined. On the other hand, option 2 only relies on string names and will only be able to validate either names at runtime: it will throw a runtime error if [code]"button_down"[/code] doesn't correspond to a signal, or if [code]"_on_button_down"[/code] is not a registered method in the object [code]self[/code]. 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.
[b]Parameter bindings and passing:[/b]
For legacy or language-specific reasons, there are also several ways to bind parameters to signals. One can pass a [code]binds[/code] [Array] to [method Object.connect] or [method Signal.connect], or use the recommended [method Callable.bind] method to create a new callable from an existing one, with the given parameter binds.
One can also pass additional parameters when emitting the signal with [method emit_signal]. The examples below show the relationship between those two types of parameters.
[codeblocks]
[gdscript]
func _ready():
# This assumes that a `Player` class exists which defines a `hit` signal.
var player = Player.new()
# Option 1: Using Callable.bind().
player.hit.connect(_on_player_hit.bind("sword", 100))
# Option 2: Using a `binds` Array in Signal.connect() (same syntax for Object.connect()).
player.hit.connect(_on_player_hit, ["sword", 100])
# Parameters added when emitting the signal are passed first.
player.emit_signal("hit", "Dark lord", 5)
# Four arguments, since we pass two when emitting (hit_by, level)
# and two 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])
[/gdscript]
[csharp]
public override void _Ready()
{
// This assumes that a `Player` class exists which defines a `Hit` signal.
var player = new Player();
// Option 1: Using Callable.Bind(). This way we can still use signals as events.
player.Hit += OnPlayerHit.Bind("sword", 100);
// Option 2: Using a `binds` Array in Signal.Connect() (same syntax for Object.Connect()).
player.Hit.Connect(OnPlayerHit, new Godot.Collections.Array{ "sword", 100 });
// Parameters added when emitting the signal are passed first.
player.EmitSignal("hit", "Dark lord", 5);
}
// Four arguments, since we pass two when emitting (hitBy, level)
// and two when connecting (weaponType, damage).
private void OnPlayerHit(string hitBy, int level, string weaponType, int damage)
{
GD.Print(String.Format("Hit by {0} (level {1}) with weapon {2} for {3} damage.", hitBy, level, weaponType, damage));
}
[/csharp]
[/codeblocks]
</description>
</method>
<method name="disconnect">
@ -175,8 +322,7 @@
<argument index="1" name="callable" type="Callable">
</argument>
<description>
[b]FIXME:[/b] The syntax changed with the addition of [Callable], this should be updated.
Disconnects a [code]signal[/code] from a [code]method[/code] on the given [code]target[/code].
Disconnects a [code]signal[/code] from a given [code]callable[/code].
If you try to disconnect a connection that does not exist, the method will throw an error. Use [method is_connected] to ensure that the connection exists.
</description>
</method>
@ -187,10 +333,16 @@
</argument>
<description>
Emits the given [code]signal[/code]. The signal must exist, so it should be a built-in signal of this class or one of its parent classes, or a user-defined signal. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example:
[codeblock]
emit_signal("hit", weapon_type, damage)
[codeblocks]
[gdscript]
emit_signal("hit", "sword", 100)
emit_signal("game_over")
[/codeblock]
[/gdscript]
[csharp]
EmitSignal("hit", "sword", 100);
EmitSignal("game_over");
[/csharp]
[/codeblocks]
</description>
</method>
<method name="free">
@ -359,8 +511,7 @@
<argument index="1" name="callable" type="Callable">
</argument>
<description>
[b]FIXME:[/b] The syntax changed with the addition of [Callable], this should be updated.
Returns [code]true[/code] if a connection exists for a given [code]signal[/code], [code]target[/code], and [code]method[/code].
Returns [code]true[/code] if a connection exists for a given [code]signal[/code] and [code]callable[/code].
</description>
</method>
<method name="is_queued_for_deletion" qualifiers="const">
@ -440,11 +591,20 @@
</argument>
<description>
Assigns a new value to the property identified by the [NodePath]. The node path should be relative to the current object and can use the colon character ([code]:[/code]) to access nested properties. Example:
[codeblock]
set_indexed("position", Vector2(42, 0))
set_indexed("position:y", -10)
print(position) # (42, -10)
[/codeblock]
[codeblocks]
[gdscript]
var node = Node2D.new()
node.set_indexed("position", Vector2(42, 0))
node.set_indexed("position:y", -10)
print(node.position) # (42, -10)
[/gdscript]
[csharp]
var node = new Node2D();
node.SetIndexed("position", new Vector2(42, 0));
node.SetIndexed("position:y", -10);
GD.Print(node.Position); // (42, -10)
[/csharp]
[/codeblocks]
</description>
</method>
<method name="set_message_translation">