I have been looking for information on Signals in Godot 4.X. I haven't been able to find much. I reached out on discord and got a ton of information and wanted to post it for anyone else needing help on the topic. Thanks to @paulloz for providing all of the following info for us!
So basically events are used as some kind of publish/subscribe system.
You can define your own events like that:
public event Something MyEvent;
// ^ Access modifier
// ^ We're defining an event
// ^ This is a type, it defines what kind of function you can subscribe this event with
// ^ This is the name of the event
When you have an event, you can subscribe to it:
MyEvent += SomeFunction;
And publish on it:
EmitSignal(SignalNames.MyEvent, ...)
Now the thing is, as you see when you define your event, you need to use a specific type to define the signature of the functions that are able to subscribe. This is usually done by defining a delegate.
public delegate void MyEventEventHandler();
// ^ This defines a type, a function taking 0 arguments and returning void
public event MyEventEventHandler MyEvent;
// ^ This defines the actual event
In Godot 4, the engine abstracts some of this for you. If you use the [Signal] attribute on a delegate, it will automatically generate the related event when you compile
public partial class MyClass : Node
{
[Signal]
public delegate void MyEventEventHandler();
}
// The partial below is going to be generated
public partial class MyClass : Node
{
public event MyEventEventHandler MyEvent;
}
In addition, it'll also generate a bunch of extra stuff like MyClass.SignalNames.MyEvent, that you can use to reference your event instead of hard-writing strings directly
Godot 4 you can not .Invoke() on the event as you generally would when using C#. Until this is implemented EmitSignal() should be used as shown above.
Eg.
public class MyNode : Node
{
[Signal]
public delegate void FooEventHandler(string str);
public override void _Ready()
{
Foo += SomeFunction; // This would work
Foo += (str) => GD.Print(str); // This would also work
}
private void SomeFunction(string str)
{
GD.Print(str);
}
}
If anyone would like to add anything or correct any mistakes let me know. I will try to keep this accurate until the official docs have been updated.