Can't queue_free() multiple instanced objects

Godot Version

4.5.1

Question

Hello, I am a beginner at godot and I am making a peggle like game and I would like to queue free

instanced pegs when the ball touches the pegs, right now I can at most queue free one peg and then

once it bounces on another peg and then this error appears: Cannot call method ‘queue_free’ on a null value.

here is the code for the ball’s hitbox:

extends Area2D


func _ready() -> void:
	area_entered.connect(_on_area_entered)

func _on_area_entered(p_area : Area2D) -> void:
	if p_area is Hurtbox:
		prints("%s hit %s at position%s"%[self, p_area, p_area.global_position])
		$"../../Pegs/Peg".queue_free()

And here is the code for the peg:

class_name Hurtbox
extends Area2D

func _ready() -> void:
	area_entered.connect(_on_area_entered)

func _on_area_entered(p_area : Area2D) -> void:
	if p_area is Hurtbox:
		pass

How to make the rest of the pegs queue free?

Grateful for any advice thank you.

In this line, you’re deleting a specific Peg that is at this specific path on the tree that you specified there.
When it’s deleted the first time, you can’t logically delete it a second time, hence the error that you’re trying to delete something that has already been deleted.

At no point in your code are you trying to delete any other Peg than this one.

What you should do instead is to grab a reference to a Peg that the ball touched and delete that Peg. I’m guessing from your code that it’d be this p_area that you should be deleting.

4 Likes

You’ll probably have an easier time if you move the code for hit detection from the player to the peg. That way you don’t have to bother with grabbing references to pegs like wchc advised.

To do that you just put a script like this in the peg’s root node, and connect the signal from the peg’s area 2D to the root node’s script via the signals menu:

extends Node2D

func _delete_self():

self.queue_free()

This way the pegs handle their own deletion. If you’re deleting lots of pegs at the same time, call_deferred(“self.queue_free()”)can be substituted to prevent errors and lag.

1 Like

Thank you very much wchc and boe_taito for your help. Greatly appriciated

1 Like