Godot Version
Godot 4.2
Question
Hi! I’m new to Godot, and I wanted to learn it in C# since it’s a useful language even outside of gamedev. I’ve been following some GDscript tutorials from Brackeys and GDQuest, converting the code to C#. Today, I ran into a problem in the GDQuest “First 2D Game” -tutorial that I can’t seem to fix.
The idea is simple: you have a bullet scene, and once that bullet scene collides with an enemy mob, it calls a function from the mob script to deal damage. So, the function is stored in mob.cs, but the on body entered -signal is in the bullet.cs.
In GDscript it’s super simple, and looks like this:
func _on_body_entered(body):
queue_free()
if body.has_method(take_damage):
body.take_damage()
This is apparently called ducktyping? However, the has_method part does not work in C#. I tried to look for a solution, and found this thread: 'Node2D' does not contain a definition for 'CollectCoin' - #4 by numbers11
Here, it is proposed that you could write something like this:
private void _on_body_entered(Node2D body)
{
QueueFree();
if (body is mob)
{
body.TakeDamage();
}
}
And that this way, the body should be cast to mob, which does include the function. This doesn’t work for me either. I get this error message for now:
CS1061: ‘Node2D’ does not contain a definition for ‘TakeDamage’ and no accessible extension method ‘TakeDamage’ accepting a first argument of type ‘Node2D’ could be found (are you missing a using directive or an assembly reference?) C:\Users\Public\Godot\GDQuest tutorial\Bullet.cs(30,10)
I’ve tried creating a reference to the mob.cs script or the mob node inside the bullet.cs script, but nothing I’ve tried works. Anyone more experience have any idea how I can get this working?
Here is the function I’m trying to call btw:
public void TakeDamage()
{
health -= 1;
if (health == 0)
{
QueueFree();
}
}
Thank you! Keep in mind that I’m almost a complete beginner and I’ve probably missed something here. I’m a bit in over my heard converting all of this script myself, but I thought it’d be a great learning experience, and I’m having fun.