C# signals

For a detailed explanation of signals in general, see the Using signals section in the step by step tutorial.

Signals are implemented using C# events, the idiomatic way to represent the observer pattern in C#. This is the recommended way to use signals in C# and the focus of this page.

In some cases it’s necessary to use the older Connect() and Disconnect() APIs. See Using Connect and Disconnect for more details.

If you encounter a System.ObjectDisposedException while handling a signal, you might be missing a signal disconnection. See Disconnecting automatically when the receiver is freed for more details.

Signals as C# events

To provide more type-safety, Godot signals are also all available through events. You can handle these events, as any other event, with the += and -= operators.

  1. Timer myTimer = GetNode<Timer>("Timer");
  2. myTimer.Timeout += () => GD.Print("Timeout!");

In addition, you can always access signal names associated with a node type through its nested SignalName class. This is useful when, for example, you want to await on a signal (see await keyword).

  1. await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);

Custom signals as C# events

To declare a custom event in your C# script, use the [Signal] attribute on a public delegate type. Note that the name of this delegate needs to end with EventHandler.

  1. [Signal]
  2. public delegate void MySignalEventHandler();
  3. [Signal]
  4. public delegate void MySignalWithArgumentEventHandler(string myString);

Once this is done, Godot will create the appropriate events automatically behind the scenes. You can then use said events as you’d do for any other Godot signal. Note that events are named using your delegate’s name minus the final EventHandler part.

  1. public override void _Ready()
  2. {
  3. MySignal += () => GD.Print("Hello!");
  4. MySignalWithArgument += SayHelloTo;
  5. }
  6. private void SayHelloTo(string name)
  7. {
  8. GD.Print($"Hello {name}!");
  9. }

Warning

If you want to connect to these signals in the editor, you will need to (re)build the project to see them appear.

You can click the Build button in the upper-right corner of the editor to do so.

Signal emission

To emit signals, use the EmitSignal method. Note that, as for signals defined by the engine, your custom signal names are listed under the nested SignalName class.

  1. public void MyMethodEmittingSignals()
  2. {
  3. EmitSignal(SignalName.MySignal);
  4. EmitSignal(SignalName.MySignalWithArgument, "World");
  5. }

In contrast with other C# events, you cannot use Invoke to raise events tied to Godot signals.

Signals support arguments of any Variant-compatible type.

Consequently, any Node or RefCounted will be compatible automatically, but custom data objects will need to inherit from GodotObject or one of its subclasses.

  1. using Godot;
  2. public partial class DataObject : GodotObject
  3. {
  4. public string MyFirstString { get; set; }
  5. public string MySecondString { get; set; }
  6. }

Bound values

Sometimes you’ll want to bind values to a signal when the connection is established, rather than (or in addition to) when the signal is emitted. To do so, you can use an anonymous function like in the following example.

Here, the Button.Pressed signal does not take any argument. But we want to use the same ModifyValue for both the “plus” and “minus” buttons. So we bind the modifier value at the time we’re connecting the signals.

  1. public int Value { get; private set; } = 1;
  2. public override void _Ready()
  3. {
  4. Button plusButton = GetNode<Button>("PlusButton");
  5. plusButton.Pressed += () => ModifyValue(1);
  6. Button minusButton = GetNode<Button>("MinusButton");
  7. minusButton.Pressed += () => ModifyValue(-1);
  8. }
  9. private void ModifyValue(int modifier)
  10. {
  11. Value += modifier;
  12. }

Signal creation at runtime

Finally, you can create custom signals directly while your game is running. Use the AddUserSignal method for that. Be aware that it should be executed before any use of said signals (either connecting to them or emitting them). Also, note that signals created this way won’t be visible through the SignalName nested class.

  1. public override void _Ready()
  2. {
  3. AddUserSignal("MyCustomSignal");
  4. EmitSignal("MyCustomSignal");
  5. }

Using Connect and Disconnect

In general, it isn’t recommended to use Connect() and Disconnect(). These APIs don’t provide as much type safety as the events. However, they’re necessary for connecting to signals defined by GDScript and passing ConnectFlags.

In the following example, pressing the button for the first time prints Greetings!. OneShot disconnects the signal, so pressing the button again does nothing.

  1. public override void _Ready()
  2. {
  3. Button button = GetNode<Button>("GreetButton");
  4. button.Connect(Button.SignalName.Pressed, Callable.From(OnButtonPressed), (uint)GodotObject.ConnectFlags.OneShot);
  5. }
  6. public void OnButtonPressed()
  7. {
  8. GD.Print("Greetings!");
  9. }

Disconnecting automatically when the receiver is freed

Normally, when any GodotObject is freed (such as any Node), Godot automatically disconnects all connections associated with that object. This happens for both signal emitters and signal receivers.

For example, a node with this code will print “Hello!” when the button is pressed, then free itself. Freeing the node disconnects the signal, so pressing the button again doesn’t do anything:

  1. public override void _Ready()
  2. {
  3. Button myButton = GetNode<Button>("../MyButton");
  4. myButton.Pressed += SayHello;
  5. }
  6. private void SayHello()
  7. {
  8. GD.Print("Hello!");
  9. Free();
  10. }

When a signal receiver is freed while the signal emitter is still alive, in some cases automatic disconnection won’t happen:

  • The signal is connected to a lambda expression that captures a variable.

  • The signal is a custom signal.

The following sections explain these cases in more detail and include suggestions for how to disconnect manually.

Note

Automatic disconnection is totally reliable if a signal emitter is freed before any of its receivers are freed. With a project style that prefers this pattern, the above limits may not be a concern.

No automatic disconnection: a lambda expression that captures a variable

If you connect to a lambda expression that captures variables, Godot can’t tell that the lambda is associated with the instance that created it. This causes this example to have potentially unexpected behavior:

  1. Timer myTimer = GetNode<Timer>("../Timer");
  2. int x = 0;
  3. myTimer.Timeout += () =>
  4. {
  5. x++; // This lambda expression captures x.
  6. GD.Print($"Tick {x} my name is {Name}");
  7. if (x == 3)
  8. {
  9. GD.Print("Time's up!");
  10. Free();
  11. }
  12. };
  1. Tick 1, my name is ExampleNode
  2. Tick 2, my name is ExampleNode
  3. Tick 3, my name is ExampleNode
  4. Time's up!
  5. [...] System.ObjectDisposedException: Cannot access a disposed object.

On tick 4, the lambda expression tries to access the Name property of the node, but the node has already been freed. This causes the exception.

To disconnect, keep a reference to the delegate created by the lambda expression and pass that to -=. For example, this node connects and disconnects using the _EnterTree and _ExitTree lifecycle methods:

  1. [Export]
  2. public Timer MyTimer { get; set; }
  3. private Action _tick;
  4. public override void _EnterTree()
  5. {
  6. int x = 0;
  7. _tick = () =>
  8. {
  9. x++;
  10. GD.Print($"Tick {x} my name is {Name}");
  11. if (x == 3)
  12. {
  13. GD.Print("Time's up!");
  14. Free();
  15. }
  16. };
  17. MyTimer.Timeout += _tick;
  18. }
  19. public override void _ExitTree()
  20. {
  21. MyTimer.Timeout -= _tick;
  22. }

In this example, Free causes the node to leave the tree, which calls _ExitTree. _ExitTree disconnects the signal, so _tick is never called again.

The lifecycle methods to use depend on what the node does. Another option is to connect to signals in _Ready and disconnect in Dispose.

Note

Godot uses Delegate.Target to determine what instance a delegate is associated with. When a lambda expression doesn’t capture a variable, the generated delegate’s Target is the instance that created the delegate. When a variable is captured, the Target instead points at a generated type that stores the captured variable. This is what breaks the association. If you want to see if a delegate will be automatically cleaned up, try checking its Target.

Callable.From doesn’t affect the Delegate.Target, so connecting a lambda that captures variables using Connect doesn’t work any better than +=.

No automatic disconnection: a custom signal

Connecting to a custom signal using += doesn’t disconnect automatically when the receiving node is freed.

To disconnect, use -= at an appropriate time. For example:

  1. [Export]
  2. public MyClass Target { get; set; }
  3. public override void _EnterTree()
  4. {
  5. Target.MySignal += OnMySignal;
  6. }
  7. public override void _ExitTree()
  8. {
  9. Target.MySignal -= OnMySignal;
  10. }

Another solution is to use Connect, which does disconnect automatically with custom signals:

  1. [Export]
  2. public MyClass Target { get; set; }
  3. public override void _EnterTree()
  4. {
  5. Target.Connect(MyClass.SignalName.MySignal, Callable.From(OnMySignal));
  6. }

User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next