How do I know when the referenced instance has been deleted

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

I have a “Main” scene in which a variable amount of Scenes are instanced. The reference is hold in a dictionary.
The instanced scenes have a visibility notifier that calls queue_free when it leaves the screen. My question is how can the main scene know which instances have been removed (the dictionary keys have to be freed up)? Or do I have to check every reference every time for whether it exists?

:bust_in_silhouette: Reply From: SIsilicon

Since you keep a reference to them in a dictionary, when they are deleted, what’s left is null reference. If you’re worried about nulls slowly filling you dictionary, you can remove the dictionary entry once the scene is freed. You have a couple of options. Here’s what I’d do.


var scenes = {} # Your dictionary

func make_a_scene_or_whatever():
    var scene = Scene.instance()
    scene.key = unique_calculated_key
    scenes[scene.key] = scene
    scene.connect("removed", self, "_on_scene_removed")
func _on_scene_removed(scene):



signal removed(scene)

var key

func _on_Visibility_screen_exited():
    emit_signal("removed", self)

You could also store a reference to the dictionary inside the scene itself, but I prefer this way.

Any questions.
BTW I came up with this on the top of my head, so it’s susceptible to errors.

SIsilicon | 2019-09-24 20:12