WHY QUEUE_FREE() ISN'T WORKING?????

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By IndigoGames

So i have this node with only one child, a rigidbody, and a scipt:

                                   
extends Spatial

onready var rigid_body = get_child(0)

func _input(event):

if event is InputEventMouseMotion and Input.is_action_pressed("Click") and Input.is_action_pressed("ui_A"):
	
	rigid_body.queue_free()
	rotate_x(event.relative.x)
	rotate_y(event.relative.y)


if Input.is_action_just_released("ui_A"):
	
	self.add_child(rigid_body

And when the condition on the 1st if statement is met the engine gives the error:
Attempt to call function ‘queue_free’ in base ‘previously freed instance’ on a null instance.
There seems to be no error in the script and the nodes rigidBody was never deleted.
Why’s that error showing up???

Also just to add, self.add_child(rigid_body) won’t work after calling queue_free(). You need to use remove_child(rigid_body) instead.

Magso | 2019-10-16 15:41

:bust_in_silhouette: Reply From: Sprowk

Important skill for programmer is to know how to debug. The message clearly states your rigid_body was already freed. My guess is that you run that code twice. First time it frees and the second time it tries again but can’t.

:bust_in_silhouette: Reply From: Eric Ellingson

I think you should try using:

if event is InputEventMouseMotion and Input.is_action_just_pressed("Click") and Input.is_action_just_pressed("ui_A"):
    # rest of your code

The difference here is that using is_action_just_pressed vs is_action_pressed is that the former will fire only once for the duration of the press, where as the latter will fire every time as long as it is still pressed. So as @Sprowk said, it is firing twice, and the second time the node has already been freed.

Just a note, depending on which input is pressed first, you probably want to use the is_action_just_pressed on only the second input you expect, because otherwise they would both need to be pressed at exactly the same time, which realistically will never happen. So if you expect the user to hold “ui_A” and then “Click”, you likely want:

if event is InputEventMouseMotion and Input.is_action_pressed("ui_A") and Input.is_action_just_pressed("Click") :
    # rest of your code