Remove_child() / queue_free() not working

Godot Version

Godot v4.2.1.stable

Question

I am trying to build out a weapon manager. When the player presses a button, the relevant weapon’s scene is loaded, instantiated and spawned as a child of the manager. This part works fine. However, when I attempt to delete the child node via a queue_free command, it doesn’t work. The weapon stays spawned and functions normally. I am completely stumped as to what I am doing wrong. My current code is below:

func _input(event):
	# spawn and equip weapon in sidearm slot
	if Input.is_action_just_pressed("equip_sidearm") and !sidearm_equipped:
		var sidearm = load("res://scenes/weapons/default_pistol/default_pistol.tscn")
		var sidearm_ready = sidearm.instantiate()
		add_child(sidearm_ready)
		sidearm_equipped = true
		if Input.is_action_just_pressed("unequip"):
			remove_child(sidearm_ready)
			sidearm_ready.queue_free()
			sidearm_equipped = false

I also tried performing the queue_free() from the child node’s own script, which did work, however when I did this I was unable to re-spawn the child node. Am I being stupid? I would appreciate any pointers as to what I am doing wrong.

Your indentations are wrong, the if Input.is_action_just_pressed("unequip"): line is nested inside the other if statement, so it never detects the unequip input.

Also you should put the variable that you use to store the sidearm instance outside the _input function, otherwise it’ll go out of scope and you can’t use it with queue_free()

1 Like

That makes complete sense and I’m kicking myself now I see it. I feel very silly. Thank you!

1 Like