get_nodes_in_group and reference breaking

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

I am using the function get_nodes_in_group and sending the array to a function and returning 1 of the nodes.
I then create a new instance of an object and set one of it’s variables to that node and add it to the scene. When the node from the group gets deleted, my new objects points to random things in scene. For example, a Tween node and an AudioStreamPlayer node. Why is it doing this, and how to I prevent it?

The variable has a [Deleted Object] that is eventually being replaced by new objects.

:bust_in_silhouette: Reply From: Zylann

You can normally check if the variable is valid using is_instance_valid(obj), but in some cases it’s unreliable. Issues were opened about this: Reference to freed object can return a random different one · Issue #32383 · godotengine/godot · GitHub

If the object you are referencing is a node, one workaround is to listen for the tree_exited signal, so when the node exits the tree you can properly set your variable to null.
Another way is to not store it in a variable but store the node path instead.

Dang, listening for the tree_exited signal is the solution I came up with before getting back here. I didn’t know the issue was on github. Thank you for helping

Picadasgalaxias | 2019-09-30 17:59