Calling a function from a body on collision in C#

should look like this

	private void OnBodyEntered(Node2D body)
		{
		
			if (body is Mob mob)
			{
		  		mob.TakeDamage();
			}
	     QueueFree();
		}

mob needed have Mob class and have method public void TakeDamage()
if there more things than enemies who can be damaged you could consider make and use interface like this

public interface IDamageable
{
    void TakeDamage(int damageTaken);
}

your Mob class needed just add interface to work,
something like:
public sealed partial class Mob: CharacterBody2D, IDamageable
still now your code is forcing you to use public void TakeDamage(int damageTaken)

public void TakeDamage(int damageTaken)
	{
		health -= damageTaken;
		if (health <= 0)
		{
			QueueFree();
		}
	}

and the damage code will look like this now

private void OnBodyEntered(Node2D body)
		{
		
			if (body is IDamageable damageable)
			{
		  		damageable.TakeDamage( 1);
			}
	     QueueFree();
		}

_on_body_entered is snake style, don’t use if your project don’t use this style, don’t mix styles of naming in one project

1 Like