Is there a way to check for ( recently ) freed object ?

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

Doesn’t need additional description :slight_smile:
Everyone knows this error : unable… : previously freed instance on a null instance.
Is there a way for checking if a node in array ceased to exist, in a way not provoking this error ? Checking Inside_scene_tree and if = null won’t work.

1 Like
:bust_in_silhouette: Reply From: Jayman2000

Yes. You can use is_instance_valid(). For example, this

var test = TestClass.new()

print(is_instance_valid(test))
test.free()
print(is_instance_valid(test))

will print “True” then “False”.

Thanks a lot :slight_smile:

Inces | 2021-02-28 14:43

4 Likes
:bust_in_silhouette: Reply From: CakeLover

As of Godot 3.5

You can also check if node.is_queued_for_deletion()

A really good example I encountered was when you have 2 Nodes A and B and both emit signals to each other and delete each other

Let’s say I have 2 Area2D nodes with the same script as such:

 extends Area2D

 func _area_entered(obj:Area2D): # area_entered signal connected
		# do something here
		obj.queue_free()

And they overlap as such:

enter image description here

You would expect that B would have more priority and hence would delete A
not giving a chance for A’s _area_entered() to be emitted and as such only A would be deleted? But nope that’s not how it works

In reality queue_free() waits for emitted signal functions to complete before deletion and as such both A & B get deleted (I learned this the hard way)


the solution? check for is_queued_for_deletion() !

 extends Area2D

 func _area_entered(obj:Area2D): # area_entered signal connected
	if(self.is_queued_for_deletion()):
	 	return
		# do something here

		obj.queue_free()

But Cakelover, you might ask, where would we actually use this?

Well this might particularly be helpful when merging the same instances like I tried

Hope this helps :slight_smile:

3 Likes