'Node2D' does not contain a definition for 'CollectCoin'

Godot Version

4.2.1

Question

hello!
I am making a game where the player can collect the coin when it enters the coin’s area 2D.
But,I am getting a problem when i call a method in the player’s script in the coin’s script using a signal. and I am using C#.

the player and the coin both are maded in a seperate scene and then added to a main scene.

the code i used to call the method from the coin’s script is :

using Godot;
using System;

public partial class money : Area2D
{
private void _on_body_entered(Node2D body)
{
if (body.HasMethod(“CollectCoin”))
{
body.CollectCoin();
QueueFree();
}
}
}

if i remove the body.CollectCoin(); line then it works fine but the collectcoin method in the player’s script does not get called.

the player’s script where the collectcoin method is :


private void CollectCoin()
{
GD.Print(“hello”);
}

the full error given by godot is :

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

I don’t use C# in Godot so I might be missing some forbidden magic in the implementation, but I can see that you’re explicitly saying that the method CollectCoin is private so normally nothing outside of the class definition’s scope can access it.

1 Like

i appreciate your reply but that is not the case!

1 Like

Thats not how things are done in a typed language such as C#.
body is a Node2D and Node2D has no method called CollectCoin. That is not dynamically discovered at runtime, but already certain when you try to compile the project, which is why it doesn’t compile. Only your Player class (whatever its named) has such a method. You seem to attempt ducktyping with HasMethod like you can do in GDScript, but that’s not the C# way. Instead, check if body is of your Player type with
if (body is Player)
{
body.CollectCoin();
QueueFree();
}

That should automatically cast body inside the if statement to Player, so you can call the method.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.