class_signal.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. :github_url: hide
  2. .. DO NOT EDIT THIS FILE!!!
  3. .. Generated automatically from Godot engine sources.
  4. .. Generator: https://github.com/godotengine/godot/tree/master/doc/tools/make_rst.py.
  5. .. XML source: https://github.com/godotengine/godot/tree/master/doc/classes/Signal.xml.
  6. .. _class_Signal:
  7. Signal
  8. ======
  9. A built-in type representing a signal of an :ref:`Object<class_Object>`.
  10. .. rst-class:: classref-introduction-group
  11. Description
  12. -----------
  13. **Signal** is a built-in :ref:`Variant<class_Variant>` type that represents a signal of an :ref:`Object<class_Object>` instance. Like all :ref:`Variant<class_Variant>` types, it can be stored in variables and passed to functions. Signals allow all connected :ref:`Callable<class_Callable>`\ s (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 :ref:`Object<class_Object>` has a given signal name using :ref:`Object.has_signal()<class_Object_method_has_signal>`.
  14. In GDScript, signals can be declared with the ``signal`` keyword. In C#, you may use the ``[Signal]`` attribute on a delegate.
  15. .. tabs::
  16. .. code-tab:: gdscript
  17. signal attacked
  18. # Additional arguments may be declared.
  19. # These arguments must be passed when the signal is emitted.
  20. signal item_dropped(item_name, amount)
  21. .. code-tab:: csharp
  22. [Signal]
  23. delegate void AttackedEventHandler();
  24. // Additional arguments may be declared.
  25. // These arguments must be passed when the signal is emitted.
  26. [Signal]
  27. delegate void ItemDroppedEventHandler(string itemName, int amount);
  28. 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.
  29. .. tabs::
  30. .. code-tab:: gdscript
  31. func _ready():
  32. var button = Button.new()
  33. # `button_down` here is a Signal Variant type. We therefore call the Signal.connect() method, not Object.connect().
  34. # See discussion below for a more in-depth overview of the API.
  35. button.button_down.connect(_on_button_down)
  36. # This assumes that a `Player` class exists, which defines a `hit` signal.
  37. var player = Player.new()
  38. # We use Signal.connect() again, and we also use the Callable.bind() method,
  39. # which returns a new Callable with the parameter binds.
  40. player.hit.connect(_on_player_hit.bind("sword", 100))
  41. func _on_button_down():
  42. print("Button down!")
  43. func _on_player_hit(weapon_type, damage):
  44. print("Hit with weapon %s for %d damage." % [weapon_type, damage])
  45. .. code-tab:: csharp
  46. public override void _Ready()
  47. {
  48. var button = new Button();
  49. // C# supports passing signals as events, so we can use this idiomatic construct:
  50. button.ButtonDown += OnButtonDown;
  51. // This assumes that a `Player` class exists, which defines a `Hit` signal.
  52. var player = new Player();
  53. // We can use lambdas when we need to bind additional parameters.
  54. player.Hit += () => OnPlayerHit("sword", 100);
  55. }
  56. private void OnButtonDown()
  57. {
  58. GD.Print("Button down!");
  59. }
  60. private void OnPlayerHit(string weaponType, int damage)
  61. {
  62. GD.Print($"Hit with weapon {weaponType} for {damage} damage.");
  63. }
  64. \ **\ ``Object.connect()`` or ``Signal.connect()``?**\
  65. As seen above, the recommended method to connect signals is not :ref:`Object.connect()<class_Object_method_connect>`. The code block below shows the four options for connecting signals, using either this legacy method or the recommended :ref:`connect()<class_Signal_method_connect>`, and using either an implicit :ref:`Callable<class_Callable>` or a manually defined one.
  66. .. tabs::
  67. .. code-tab:: gdscript
  68. func _ready():
  69. var button = Button.new()
  70. # Option 1: Object.connect() with an implicit Callable for the defined function.
  71. button.connect("button_down", _on_button_down)
  72. # Option 2: Object.connect() with a constructed Callable using a target object and method name.
  73. button.connect("button_down", Callable(self, "_on_button_down"))
  74. # Option 3: Signal.connect() with an implicit Callable for the defined function.
  75. button.button_down.connect(_on_button_down)
  76. # Option 4: Signal.connect() with a constructed Callable using a target object and method name.
  77. button.button_down.connect(Callable(self, "_on_button_down"))
  78. func _on_button_down():
  79. print("Button down!")
  80. .. code-tab:: csharp
  81. public override void _Ready()
  82. {
  83. var button = new Button();
  84. // Option 1: In C#, we can use signals as events and connect with this idiomatic syntax:
  85. button.ButtonDown += OnButtonDown;
  86. // Option 2: GodotObject.Connect() with a constructed Callable from a method group.
  87. button.Connect(Button.SignalName.ButtonDown, Callable.From(OnButtonDown));
  88. // Option 3: GodotObject.Connect() with a constructed Callable using a target object and method name.
  89. button.Connect(Button.SignalName.ButtonDown, new Callable(this, MethodName.OnButtonDown));
  90. }
  91. private void OnButtonDown()
  92. {
  93. GD.Print("Button down!");
  94. }
  95. While all options have the same outcome (``button``'s :ref:`BaseButton.button_down<class_BaseButton_signal_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`` :ref:`Callable<class_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.
  96. \ **Binding and passing parameters:**\
  97. The syntax to bind parameters is through :ref:`Callable.bind()<class_Callable_method_bind>`, which returns a copy of the :ref:`Callable<class_Callable>` with its parameters bound.
  98. When calling :ref:`emit()<class_Signal_method_emit>` or :ref:`Object.emit_signal()<class_Object_method_emit_signal>`, the signal parameters can be also passed. The examples below show the relationship between these signal parameters and bound parameters.
  99. .. tabs::
  100. .. code-tab:: gdscript
  101. func _ready():
  102. # This assumes that a `Player` class exists, which defines a `hit` signal.
  103. var player = Player.new()
  104. # Using Callable.bind().
  105. player.hit.connect(_on_player_hit.bind("sword", 100))
  106. # Parameters added when emitting the signal are passed first.
  107. player.hit.emit("Dark lord", 5)
  108. # We pass two arguments when emitting (`hit_by`, `level`),
  109. # and bind two more arguments when connecting (`weapon_type`, `damage`).
  110. func _on_player_hit(hit_by, level, weapon_type, damage):
  111. print("Hit by %s (level %d) with weapon %s for %d damage." % [hit_by, level, weapon_type, damage])
  112. .. code-tab:: csharp
  113. public override void _Ready()
  114. {
  115. // This assumes that a `Player` class exists, which defines a `Hit` signal.
  116. var player = new Player();
  117. // Using lambda expressions that create a closure that captures the additional parameters.
  118. // The lambda only receives the parameters defined by the signal's delegate.
  119. player.Hit += (hitBy, level) => OnPlayerHit(hitBy, level, "sword", 100);
  120. // Parameters added when emitting the signal are passed first.
  121. player.EmitSignal(SignalName.Hit, "Dark lord", 5);
  122. }
  123. // We pass two arguments when emitting (`hit_by`, `level`),
  124. // and bind two more arguments when connecting (`weapon_type`, `damage`).
  125. private void OnPlayerHit(string hitBy, int level, string weaponType, int damage)
  126. {
  127. GD.Print($"Hit by {hitBy} (level {level}) with weapon {weaponType} for {damage} damage.");
  128. }
  129. .. note::
  130. There are notable differences when using this API with C#. See :ref:`doc_c_sharp_differences` for more information.
  131. .. rst-class:: classref-introduction-group
  132. Tutorials
  133. ---------
  134. - :doc:`Using Signals <../getting_started/step_by_step/signals>`
  135. - `GDScript Basics <../tutorials/scripting/gdscript/gdscript_basics.html#signals>`__
  136. .. rst-class:: classref-reftable-group
  137. Constructors
  138. ------------
  139. .. table::
  140. :widths: auto
  141. +-----------------------------+------------------------------------------------------------------------------------------------------------------------------------------+
  142. | :ref:`Signal<class_Signal>` | :ref:`Signal<class_Signal_constructor_Signal>`\ (\ ) |
  143. +-----------------------------+------------------------------------------------------------------------------------------------------------------------------------------+
  144. | :ref:`Signal<class_Signal>` | :ref:`Signal<class_Signal_constructor_Signal>`\ (\ from\: :ref:`Signal<class_Signal>`\ ) |
  145. +-----------------------------+------------------------------------------------------------------------------------------------------------------------------------------+
  146. | :ref:`Signal<class_Signal>` | :ref:`Signal<class_Signal_constructor_Signal>`\ (\ object\: :ref:`Object<class_Object>`, signal\: :ref:`StringName<class_StringName>`\ ) |
  147. +-----------------------------+------------------------------------------------------------------------------------------------------------------------------------------+
  148. .. rst-class:: classref-reftable-group
  149. Methods
  150. -------
  151. .. table::
  152. :widths: auto
  153. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  154. | :ref:`int<class_int>` | :ref:`connect<class_Signal_method_connect>`\ (\ callable\: :ref:`Callable<class_Callable>`, flags\: :ref:`int<class_int>` = 0\ ) |
  155. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  156. | |void| | :ref:`disconnect<class_Signal_method_disconnect>`\ (\ callable\: :ref:`Callable<class_Callable>`\ ) |
  157. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  158. | |void| | :ref:`emit<class_Signal_method_emit>`\ (\ ...\ ) |vararg| |const| |
  159. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  160. | :ref:`Array<class_Array>` | :ref:`get_connections<class_Signal_method_get_connections>`\ (\ ) |const| |
  161. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  162. | :ref:`StringName<class_StringName>` | :ref:`get_name<class_Signal_method_get_name>`\ (\ ) |const| |
  163. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  164. | :ref:`Object<class_Object>` | :ref:`get_object<class_Signal_method_get_object>`\ (\ ) |const| |
  165. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  166. | :ref:`int<class_int>` | :ref:`get_object_id<class_Signal_method_get_object_id>`\ (\ ) |const| |
  167. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  168. | :ref:`bool<class_bool>` | :ref:`has_connections<class_Signal_method_has_connections>`\ (\ ) |const| |
  169. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  170. | :ref:`bool<class_bool>` | :ref:`is_connected<class_Signal_method_is_connected>`\ (\ callable\: :ref:`Callable<class_Callable>`\ ) |const| |
  171. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  172. | :ref:`bool<class_bool>` | :ref:`is_null<class_Signal_method_is_null>`\ (\ ) |const| |
  173. +-------------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
  174. .. rst-class:: classref-reftable-group
  175. Operators
  176. ---------
  177. .. table::
  178. :widths: auto
  179. +-------------------------+-------------------------------------------------------------------------------------------------+
  180. | :ref:`bool<class_bool>` | :ref:`operator !=<class_Signal_operator_neq_Signal>`\ (\ right\: :ref:`Signal<class_Signal>`\ ) |
  181. +-------------------------+-------------------------------------------------------------------------------------------------+
  182. | :ref:`bool<class_bool>` | :ref:`operator ==<class_Signal_operator_eq_Signal>`\ (\ right\: :ref:`Signal<class_Signal>`\ ) |
  183. +-------------------------+-------------------------------------------------------------------------------------------------+
  184. .. rst-class:: classref-section-separator
  185. ----
  186. .. rst-class:: classref-descriptions-group
  187. Constructor Descriptions
  188. ------------------------
  189. .. _class_Signal_constructor_Signal:
  190. .. rst-class:: classref-constructor
  191. :ref:`Signal<class_Signal>` **Signal**\ (\ ) :ref:`🔗<class_Signal_constructor_Signal>`
  192. Constructs an empty **Signal** with no object nor signal name bound.
  193. .. rst-class:: classref-item-separator
  194. ----
  195. .. rst-class:: classref-constructor
  196. :ref:`Signal<class_Signal>` **Signal**\ (\ from\: :ref:`Signal<class_Signal>`\ )
  197. Constructs a **Signal** as a copy of the given **Signal**.
  198. .. rst-class:: classref-item-separator
  199. ----
  200. .. rst-class:: classref-constructor
  201. :ref:`Signal<class_Signal>` **Signal**\ (\ object\: :ref:`Object<class_Object>`, signal\: :ref:`StringName<class_StringName>`\ )
  202. Creates a **Signal** object referencing a signal named ``signal`` in the specified ``object``.
  203. .. rst-class:: classref-section-separator
  204. ----
  205. .. rst-class:: classref-descriptions-group
  206. Method Descriptions
  207. -------------------
  208. .. _class_Signal_method_connect:
  209. .. rst-class:: classref-method
  210. :ref:`int<class_int>` **connect**\ (\ callable\: :ref:`Callable<class_Callable>`, flags\: :ref:`int<class_int>` = 0\ ) :ref:`🔗<class_Signal_method_connect>`
  211. Connects this signal to the specified ``callable``. Optional ``flags`` can be also added to configure the connection's behavior (see :ref:`ConnectFlags<enum_Object_ConnectFlags>` constants). You can provide additional arguments to the connected ``callable`` by using :ref:`Callable.bind()<class_Callable_method_bind>`.
  212. A signal can only be connected once to the same :ref:`Callable<class_Callable>`. If the signal is already connected, this method returns :ref:`@GlobalScope.ERR_INVALID_PARAMETER<class_@GlobalScope_constant_ERR_INVALID_PARAMETER>` and generates an error, unless the signal is connected with :ref:`Object.CONNECT_REFERENCE_COUNTED<class_Object_constant_CONNECT_REFERENCE_COUNTED>`. To prevent this, use :ref:`is_connected()<class_Signal_method_is_connected>` first to check for existing connections.
  213. ::
  214. for button in $Buttons.get_children():
  215. button.pressed.connect(_on_pressed.bind(button))
  216. func _on_pressed(button):
  217. print(button.name, " was pressed")
  218. \ **Note:** If the ``callable``'s object is freed, the connection will be lost.
  219. .. rst-class:: classref-item-separator
  220. ----
  221. .. _class_Signal_method_disconnect:
  222. .. rst-class:: classref-method
  223. |void| **disconnect**\ (\ callable\: :ref:`Callable<class_Callable>`\ ) :ref:`🔗<class_Signal_method_disconnect>`
  224. Disconnects this signal from the specified :ref:`Callable<class_Callable>`. If the connection does not exist, generates an error. Use :ref:`is_connected()<class_Signal_method_is_connected>` to make sure that the connection exists.
  225. .. rst-class:: classref-item-separator
  226. ----
  227. .. _class_Signal_method_emit:
  228. .. rst-class:: classref-method
  229. |void| **emit**\ (\ ...\ ) |vararg| |const| :ref:`🔗<class_Signal_method_emit>`
  230. Emits this signal. All :ref:`Callable<class_Callable>`\ s connected to this signal will be triggered. This method supports a variable number of arguments, so parameters can be passed as a comma separated list.
  231. .. rst-class:: classref-item-separator
  232. ----
  233. .. _class_Signal_method_get_connections:
  234. .. rst-class:: classref-method
  235. :ref:`Array<class_Array>` **get_connections**\ (\ ) |const| :ref:`🔗<class_Signal_method_get_connections>`
  236. Returns an :ref:`Array<class_Array>` of connections for this signal. Each connection is represented as a :ref:`Dictionary<class_Dictionary>` that contains three entries:
  237. - ``signal`` is a reference to this signal;
  238. - ``callable`` is a reference to the connected :ref:`Callable<class_Callable>`;
  239. - ``flags`` is a combination of :ref:`ConnectFlags<enum_Object_ConnectFlags>`.
  240. .. rst-class:: classref-item-separator
  241. ----
  242. .. _class_Signal_method_get_name:
  243. .. rst-class:: classref-method
  244. :ref:`StringName<class_StringName>` **get_name**\ (\ ) |const| :ref:`🔗<class_Signal_method_get_name>`
  245. Returns the name of this signal.
  246. .. rst-class:: classref-item-separator
  247. ----
  248. .. _class_Signal_method_get_object:
  249. .. rst-class:: classref-method
  250. :ref:`Object<class_Object>` **get_object**\ (\ ) |const| :ref:`🔗<class_Signal_method_get_object>`
  251. Returns the object emitting this signal.
  252. .. rst-class:: classref-item-separator
  253. ----
  254. .. _class_Signal_method_get_object_id:
  255. .. rst-class:: classref-method
  256. :ref:`int<class_int>` **get_object_id**\ (\ ) |const| :ref:`🔗<class_Signal_method_get_object_id>`
  257. Returns the ID of the object emitting this signal (see :ref:`Object.get_instance_id()<class_Object_method_get_instance_id>`).
  258. .. rst-class:: classref-item-separator
  259. ----
  260. .. _class_Signal_method_has_connections:
  261. .. rst-class:: classref-method
  262. :ref:`bool<class_bool>` **has_connections**\ (\ ) |const| :ref:`🔗<class_Signal_method_has_connections>`
  263. Returns ``true`` if any :ref:`Callable<class_Callable>` is connected to this signal.
  264. .. rst-class:: classref-item-separator
  265. ----
  266. .. _class_Signal_method_is_connected:
  267. .. rst-class:: classref-method
  268. :ref:`bool<class_bool>` **is_connected**\ (\ callable\: :ref:`Callable<class_Callable>`\ ) |const| :ref:`🔗<class_Signal_method_is_connected>`
  269. Returns ``true`` if the specified :ref:`Callable<class_Callable>` is connected to this signal.
  270. .. rst-class:: classref-item-separator
  271. ----
  272. .. _class_Signal_method_is_null:
  273. .. rst-class:: classref-method
  274. :ref:`bool<class_bool>` **is_null**\ (\ ) |const| :ref:`🔗<class_Signal_method_is_null>`
  275. Returns ``true`` if this **Signal** has no object and the signal name is empty. Equivalent to ``signal == Signal()``.
  276. .. rst-class:: classref-section-separator
  277. ----
  278. .. rst-class:: classref-descriptions-group
  279. Operator Descriptions
  280. ---------------------
  281. .. _class_Signal_operator_neq_Signal:
  282. .. rst-class:: classref-operator
  283. :ref:`bool<class_bool>` **operator !=**\ (\ right\: :ref:`Signal<class_Signal>`\ ) :ref:`🔗<class_Signal_operator_neq_Signal>`
  284. Returns ``true`` if the signals do not share the same object and name.
  285. .. rst-class:: classref-item-separator
  286. ----
  287. .. _class_Signal_operator_eq_Signal:
  288. .. rst-class:: classref-operator
  289. :ref:`bool<class_bool>` **operator ==**\ (\ right\: :ref:`Signal<class_Signal>`\ ) :ref:`🔗<class_Signal_operator_eq_Signal>`
  290. Returns ``true`` if both signals share the same object and name.
  291. .. |virtual| replace:: :abbr:`virtual (This method should typically be overridden by the user to have any effect.)`
  292. .. |required| replace:: :abbr:`required (This method is required to be overridden when extending its base class.)`
  293. .. |const| replace:: :abbr:`const (This method has no side effects. It doesn't modify any of the instance's member variables.)`
  294. .. |vararg| replace:: :abbr:`vararg (This method accepts any number of arguments after the ones described here.)`
  295. .. |constructor| replace:: :abbr:`constructor (This method is used to construct a type.)`
  296. .. |static| replace:: :abbr:`static (This method doesn't need an instance to be called, so it can be called directly using the class name.)`
  297. .. |operator| replace:: :abbr:`operator (This method describes a valid operator to use with this type as left-hand operand.)`
  298. .. |bitfield| replace:: :abbr:`BitField (This value is an integer composed as a bitmask of the following flags.)`
  299. .. |void| replace:: :abbr:`void (No return value.)`