Area2D area_entered signal is passing null

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TTG

I come from a programming background and so I am trying to use Godot mostly through programming.

I wanted to create my own type of node “Boulder” and detect when it collides with my player.

I created the boulder node using only GDScript:

# boulder.gd
class_name Boulder

var area
func _ready():
	# Set up the collision for the boulder
	area = Area2D.new()
    # (omitted) set sollision mask, collision shape, etc
	add_child(area)

Then I created my player through the editor.
I added an Area2D node to my player, and used the edtior to connect the area_entered signal to the player GDscript:

# Player.gd
func _on_Area2D_area_entered(boulder: Boulder):
    print("Collided with: ", boulder)

I then have a scene where I spawn a Boulder so that it will fall onto the player.

However, when they collide the boulder value passed to _on_Area2D_area_entered is null.

Not sure what is happening here.

:bust_in_silhouette: Reply From: Lola

Hello,
the area_entered signal has the Area that entered has an argument (the one stored in area in your script) which is not a Boulder (what does Boulder extends?). You are type casting the Area as a Boulder in your method, resulting in null.

Thank you! I didn’t realize the type casting would cause the result to be null.

If I change Boulder to extend Area2D the above code should work as expected?

TTG | 2021-08-16 18:42