Invalid type in function '_collide' in base 'Area2D (Hitbox)'. The Object-derived class of argument 1 (previously freed) is not a subclass of the expected argument class. Help, please

Godot Version

Godot 4.2.1 Engine

Question

Hello, gyes :sunglasses: :sunglasses: :sunglasses:.I’m trying to do damage to the tree, but for some reason every deleted object is added to the body, it’s clearer in the video.
It is hitbox

extends Area2D
class_name Hitbox

@export var damage: int = 1
var knockback_direction: Vector2 = Vector2.ZERO
@export var knockback_force: int = 300

var body_inside: bool = false

@onready var collision_shape: CollisionShape2D = get_child(0)
@onready var timer: Timer = Timer.new()


func _init() -> void:
	var __ = connect("body_entered", Callable(self, "_on_body_entered"))
	__ = connect("body_exited", Callable(self, "_on_body_exited"))
func _on_body_entered(body: Node2D) -> void:
	body_inside = true
	timer.start()
	while body_inside:
		print(body)
               # if body != null:
		_collide(body)
		await timer.timeout


func _on_body_exited(_body: Node2D) -> void:
	body_inside = false
	timer.stop()

func _collide(body: Node2D) -> void:
	if body == null or not body.has_method("take_damage"):
		queue_free()
	else:
		body.take_damage(damage, knockback_direction, knockback_force)

It is take damage

func take_damage(damage: int, _pass, __pass):
	if state_machine.state != state_machine.states.mined and state_machine.state != state_machine.states.dead:
		self.hp -= damage
		print(hp)
		if hp > 0:
			state_machine.set_state(state_machine.states.mined)
		else:
			state_machine.set_state(state_machine.states.dead)

изображение

the link is to the video, but beginners can’t just download the video

I don’t understand that while true loop on body entered function. It looks like a one off interaction which makes the while loop and timer pointless imo.

That on body entered gets called once for every object in the collision layer it senses. The hitbox could end up deleting itself if the check fails. Whenever it senses something that cannot take damage.

I watched the video I didn’t see an obvious issue.

if body != null:

this thing in the video does not skip empty objects, for some reason these objects accumulate in the body

<Freed Object>
<Freed Object>
<Freed Object>
<Freed Object>
<Freed Object>
<Freed Object>
<Freed Object>
@StaticBody2D@5:<StaticBody2D#34393294265>

I do not know what other way there is for the enemy to take damage while in hitbox collision
This is link to tutorial

Body will never be null.

Those logs are happening because the function _on_body_entered got called many times and the hit box queue_freed itself many times.