"Attempt to call function on a null instance" error when 2 NPC try to delete the same item

Godot Version

4.2.1

Question

I have a probelm where I get the error

“Attempt to call function ‘queue_free’ in base ‘previously freed’ on a null instance.”

Been trying to debug this for hours now, there is no other place where queue_free() is called and I am pretty sure the error occurs because two instances of the NPC this function belongs to try to execute it at the same time. I tried to fix that by checking for “is_queued_for_deletion()” but that doesn’t stop it.

Does anyone have an idea what I might be missing or can explain why this still happens?

func _on_food_zone_body_entered(body):
	if body is Fish and body.is_queued_for_deletion() == false:
		current_state = WAIT
		$CPUParticles2D.emitting = true
		await get_tree().create_timer(2).timeout
		body.queue_free()
		$CPUParticles2D.emitting = false
	elif body is Player:
		current_state = FLEE
	else:
		randomize_wander()
		current_state = WANDER

Try with @GlobalScope.is_instance_valid()

func _on_food_zone_body_entered(body):
	if not is_instance_valid(body): 
		return
		
	# the rest of the code
1 Like

I tried and it still reacts the same way.
Is it maybe because the timer makes it possible for a different NPC to get to it before it is invalid?

Have you tried to check, if body is valid after waiting 2 seconds, just before calling queue_free()?

Great idea!
That worked.
First I had removed the timer completely but this way I can still use it and just check validity after it expires. Thanks for the fast help :slightly_smiling_face:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.