What's the best way to interact with a custom class on collision?

Godot Version

4.3.stable.mono

Question

Very new to Godot here, so thanks in advance (adthanksvance)! I’m trying to interact with a game object that has a script on it, from within another script when the objects collide. I’ll give you all what I’m trying at the moment—hopefully that can at least demonstrate what I thought I could do. I have a Shirt:

public partial class Shirt : Area2D
{
	[Export]
	public String color { get; set; } = "white";
}

And I have a Player, which has the following method that is connected to the area_entered signal of an Area2D:

public partial class Player : RigidBody2D
{
// ...
	private void OnBodyEntered(Node2D body)
	{
		GD.Print("I ran into " + body.Name);
		if (body is Shirt shirt) {
			GD.Print("It's a " + shirt.color + " shirt");
		}
	}
// ...
}

When I debug this, I can see that the body is at least an Area2D, but the body is Shirt shirt part is not working as I had hoped. I’m pretty sure this is because I’m trying to derive a derived class (Shirt) from a base class (Area2D). My goal here is for the Player to be able to get the Shirts color when they collide. Is there a Godot-y way to achieve this?

Are you sure you’re using the correct signal? The function signal should be OnAreaEntered(Area2D area), the way your signal callback is write looks like you used body_entered instead.

1 Like

So far so good, as matheusmdx recommends. Assuming the collisions are configured correctly and the script (type) is on the Node2D that is passed to the handler.

Tried to test getting custom class myself and it feels like it’s broken…
I suggest to create dedicated variable in your class, just for checking if this is a “Shirt”.
Also you can use groups.