Cannot call method 'queue_free' on a previously freed instance

Godot Version

godot 4

Question

Hello there! I’m currently making a door that opens with a key. the door can not open if you dont have the key. so far, i can open the door but the thing is, the area2d will still detect the player after the door is opened.

the idea is to make a door that blocks the player if they dont have a key. and entering the door area will remove that block by freeing the collision shape. this is my code for the door:

extends Area2D

@onready var animated_sprite_2d: AnimatedSprite2D = $"../AnimatedSprite2D"
@onready var timer: Timer = $Timer
@onready var collision_shape_2d: CollisionShape2D = $"../CollisionShape2D"
@onready var audio_stream_player_2d: AudioStreamPlayer2D = $"../AudioStreamPlayer2D"


func _on_body_entered(body: Node2D) -> void:
	if body is rangga:
		if body.has_key == true:
			animated_sprite_2d.play("open")
			collision_shape_2d.queue_free()
			audio_stream_player_2d.play()
			timer.start()
			
		else:
			pass


func _on_timer_timeout() -> void:
	pass

so, after i open this door and free the collision mask attached to the door, godot sends me an error message:
Cannot call method ‘queue_free’ on a previously freed instance.

I think the error fires when you reenter your area3D. Since your collision shape is already freed your code can’t free it again and throws an error.
A potential fix for this would be to use a boolen variable “is_locked” which only executed your code if the door is locked.

...
var is_locked : bool = true

func _on_body_entered(body: Node2D) -> void:
	if body is rangga:
		if is_locked and body.has_key:
			is_locked = false
			animated_sprite_2d.play("open")
			collision_shape_2d.queue_free()
			audio_stream_player_2d.play()
			timer.start()
			
		else:
			pass

hey that worked! You just saved my finals :sweat_smile: thanks, I’ll keep that in mind the next time i’m making something with conditions

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