Issue with connecting a custom signal with C#

Godot Version

4.2

Question

I’m running into an issue with trying to connect custom signals with C#. In my code, I’m trying to connect a custom signal from a Button node “startbattle” to an AnimatedSprite2D node “card” that is a child of startbattle’s sibling Node2D “hand”. The connecting from code in Button “startbattle” looks like this:

[Signal]
public delegate void KeyboardStartBattleEventHandler();

and then later:

EmitSignal(SignalName.KeyboardStartBattle);

In my receiving AnimatedSprite2D node “card” I have:

    var startbattle = GetNode<Node2D>("..").GetNode<Button>("../startbattle");
    startbattle.KeyboardStartBattle += OnStartBattlePressed;

This code prevents Godot from building the project and gives the following error in both Godot and VS:

‘Button’ does not contain a definition for ‘KeyboardStartBattle’ and no accessible extension method ‘KeyboardStartBattle’ accepting a first argument of type ‘Button’ could be found (are you missing a using directive or an assembly reference?)

I’m not sure what I’m missing when it comes to getting this signal to connect. Anyone have any ideas?

The compiler complains because it cannot find KeyboardStartBattle in the type Button. This makes sense since Button does not define it. Instead it is defined in your custom class that inherits from Button (whatever its name is). Therefore, you need to cast it to that type, so that the compiler knows where to look for the function:

// Replace [YourButtonClass] with your actual button class
// Also you don't need multiple getNode, you can pass the full relative path directly
var startbattle = GetNode<[YourButtonClass]>("../../startbattle");
1 Like

Thanks a bunch! That did it!