Search code examples
c#godot

C#: Callback code won't be generated, please add it manually


I'm working through a Godot tutorial and it asks me to create a signal for an Area2D's body_entered signal. However, I'm using C# instead of GDScript. When I go to connect a signal to a method, I get the warning "C#: Callback code won't be generated, please add it manually":

The "Connect a Signal to a Method" dialog for _on_area_2d_body_entered with the warning

How do I add the callback code manually?


Solution

  • The Godot tutorial has a section on Using signals which can be helpful here.

    The tutorial has a note on conventions here:

    By convention, we name these callback methods in GDScript as "_on_node_name_signal_name" and in C# as "OnNodeNameSignalName". Here, it'll be "_on_timer_timeout" for GDScript and OnTimerTimeout() for C#.

    We'll want to use Pascal case for our method name. I've renamed mine from _on_area_2d_body_entered to OnArea2DBodyEntered:

    The "Connect a Signal to a Method" dialog with the warning, this time with OnArea2DBodyEntered instead of _on_area_2d_body_entered

    After pressing "Connect", if we look at the Node tab, we can see that the method signature requires that we take in a Node2D:

    body_entered(body: Node2D)

    We need to go to our script file and manually add this code:

    public void OnArea2DBodyEntered(Node2D body)
    {
        // Replace with function body
    }
    

    After that, you can continue wiring up your signal by implementing the function body. For example:

    public void OnArea2DBodyEntered(Node2D body)
    {
        if (body is Player)
        {
            GD.Print("Player entered");
        }
    }