c_sharp_signals.rst 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. .. _doc_c_sharp_signals:
  2. C# signals
  3. ==========
  4. For a detailed explanation of signals in general, see the :ref:`doc_signals` section in the step
  5. by step tutorial.
  6. Signals are implemented using C# events, the idiomatic way to represent
  7. :ref:`the observer pattern<doc_key_concepts_signals>` in C#. This is the
  8. recommended way to use signals in C# and the focus of this page.
  9. In some cases it's necessary to use the older
  10. :ref:`Connect()<class_object_method_connect>` and
  11. :ref:`Disconnect()<class_object_method_disconnect>` APIs.
  12. See :ref:`using_connect_and_disconnect` for more details.
  13. Signals as C# events
  14. --------------------
  15. To provide more type-safety, Godot signals are also all available through `events <https://learn.microsoft.com/en-us/dotnet/csharp/events-overview>`_.
  16. You can handle these events, as any other event, with the ``+=`` and ``-=`` operators.
  17. .. code-block:: csharp
  18. Timer myTimer = GetNode<Timer>("Timer");
  19. myTimer.Timeout += () => GD.Print("Timeout!");
  20. In addition, you can always access signal names associated with a node type through its nested
  21. ``SignalName`` class. This is useful when, for example, you want to await on a signal (see :ref:`doc_c_sharp_differences_await`).
  22. .. code-block:: csharp
  23. await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
  24. .. warning::
  25. While all engine signals connected as events are automatically disconnected when nodes are freed, custom
  26. signals connected using ``+=`` aren't. Meaning that: you will need to manually disconnect (using ``-=``)
  27. all the custom signals you connected as C# events (using ``+=``).
  28. An alternative to manually disconnecting using ``-=`` is to
  29. :ref:`use Connect <using_connect_and_disconnect>` rather than ``+=``.
  30. See `Godot issue #70414 <https://github.com/godotengine/godot/issues/70414>`_.
  31. Custom signals as C# events
  32. ---------------------------
  33. To declare a custom event in your C# script, use the ``[Signal]`` attribute on a public delegate type.
  34. Note that the name of this delegate needs to end with ``EventHandler``.
  35. .. code-block:: csharp
  36. [Signal]
  37. public delegate void MySignalEventHandler();
  38. [Signal]
  39. public delegate void MySignalWithArgumentEventHandler(string myString);
  40. Once this is done, Godot will create the appropriate events automatically behind the scenes. You
  41. can then use said events as you'd do for any other Godot signal. Note that events are named using
  42. your delegate's name minus the final ``EventHandler`` part.
  43. .. code-block:: csharp
  44. public override void _Ready()
  45. {
  46. MySignal += () => GD.Print("Hello!");
  47. MySignalWithArgument += SayHelloTo;
  48. }
  49. private void SayHelloTo(string name)
  50. {
  51. GD.Print($"Hello {name}!");
  52. }
  53. .. warning::
  54. If you want to connect to these signals in the editor, you will need to (re)build the project
  55. to see them appear.
  56. You can click the **Build** button in the upper-right corner of the editor to do so.
  57. Signal emission
  58. ---------------
  59. To emit signals, use the ``EmitSignal`` method. Note that, as for signals defined by the engine,
  60. your custom signal names are listed under the nested ``SignalName`` class.
  61. .. code-block:: csharp
  62. public void MyMethodEmittingSignals()
  63. {
  64. EmitSignal(SignalName.MySignal);
  65. EmitSignal(SignalName.MySignalWithArgument, "World");
  66. }
  67. In contrast with other C# events, you cannot use ``Invoke`` to raise events tied to Godot signals.
  68. Signals support arguments of any :ref:`Variant-compatible type <c_sharp_variant_compatible_types>`.
  69. Consequently, any ``Node`` or ``RefCounted`` will be compatible automatically, but custom data objects will need
  70. to inherit from ``GodotObject`` or one of its subclasses.
  71. .. code-block:: csharp
  72. using Godot;
  73. public partial class DataObject : GodotObject
  74. {
  75. public string MyFirstString { get; set; }
  76. public string MySecondString { get; set; }
  77. }
  78. Bound values
  79. ------------
  80. Sometimes you'll want to bind values to a signal when the connection is established, rather than
  81. (or in addition to) when the signal is emitted. To do so, you can use an anonymous function like in
  82. the following example.
  83. Here, the :ref:`Button.Pressed <class_BaseButton_signal_pressed>` signal do not take any argument. But we
  84. want to use the same ``ModifyValue`` for both the "plus" and "minus" buttons. So we bind the
  85. modifier value at the time we're connecting the signals.
  86. .. code-block:: csharp
  87. public int Value { get; private set; } = 1;
  88. public override void _Ready()
  89. {
  90. Button plusButton = GetNode<Button>("PlusButton");
  91. plusButton.Pressed += () => ModifyValue(1);
  92. Button minusButton = GetNode<Button>("MinusButton");
  93. minusButton.Pressed += () => ModifyValue(-1);
  94. }
  95. private void ModifyValue(int modifier)
  96. {
  97. Value += modifier;
  98. }
  99. Signal creation at runtime
  100. --------------------------
  101. Finally, you can create custom signals directly while your game is running. Use the ``AddUserSignal``
  102. method for that. Be aware that it should be executed before any use of said signals (either
  103. connecting to them or emitting them). Also, note that signals created this way won't be visible through the
  104. ``SignalName`` nested class.
  105. .. code-block:: csharp
  106. public override void _Ready()
  107. {
  108. AddUserSignal("MyCustomSignal");
  109. EmitSignal("MyCustomSignal");
  110. }
  111. .. _using_connect_and_disconnect:
  112. Using Connect and Disconnect
  113. ----------------------------
  114. In general, it isn't recommended to use
  115. :ref:`Connect()<class_object_method_connect>` and
  116. :ref:`Disconnect()<class_object_method_disconnect>`. These APIs don't provide as
  117. much type safety as the events. However, they're necessary for
  118. :ref:`connecting to signals defined by GDScript <connecting_to_signals_cross_language>`
  119. and passing :ref:`ConnectFlags<enum_Object_ConnectFlags>`.
  120. In the following example, pressing the button for the first time prints
  121. ``Greetings!``. ``OneShot`` disconnects the signal, so pressing the button again
  122. does nothing.
  123. .. code-block:: csharp
  124. public override void _Ready()
  125. {
  126. Button button = GetNode<Button>("GreetButton");
  127. button.Connect(Button.SignalName.Pressed, Callable.From(OnButtonPressed), (uint)GodotObject.ConnectFlags.OneShot);
  128. }
  129. public void OnButtonPressed()
  130. {
  131. GD.Print("Greetings!");
  132. }