Detect if an object reference is Freed?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hearto
:warning: Old Version Published before Godot 3 was released.

I have an a reference of an object and I want to detect if the object has been freed with queue_free.
This is the output after the object has been freed
print("obj:" + str(obj))

before queue free
obj: [RigidBody2D:1000]
after queue free
obj: [Deleted Object]

I want to test something like


obj == null don’t work on this case.

So How to do this on Godot?

:bust_in_silhouette: Reply From: kubecz3k

While you know the object is stll alive:

var wr = weakref(object);

Then you can check like this:

if (!wr.get_ref()):
     #object is erased
    #object is fine so you can do something with it:

This is exactly what @hearto and I were looking for. Thanks you!

agus | 2016-04-23 02:00

Can someone tell me why a while loop causes execution to freeze? E.g.

while ! wr.get_ref():
    # object is erased

stevepop | 2017-08-18 20:13

You saved my life, thanks a lot!!!

Chao Yu | 2017-11-17 15:41

:bust_in_silhouette: Reply From: Jay Kyburz

As of 3.1.1 you can call

Thank you! Awesome. Much easier than the weakref

NOAHGengo | 2020-05-17 20:24

:bust_in_silhouette: Reply From: gruen

i put every item in groups.
you can check the group how many members it has or if an specific objekt is inside it.

if it has been freed the group dosnt contain it anymore.

:bust_in_silhouette: Reply From: JulSams

Use the signal “tree_exited” to know when something was freed. This is indirect. It will work on items that are in the scene tree.
Warning: if an item is never added to the scene tree, this will not work.