How to Queue_Free() Correctly?

godot-4

New to Godot and I’m trying to learn how to use queue_free() correctly.

Inside the gameScene:

var new_scene = scene.instantiate()
new_scene.connect("removeNewScene, _remove_scene)
new_scene_margin_container.add_child(new_scene)
new_scene_margin_container.visible = true

Above is basically how I add the new scene (in this example a quick game explainer) to the tree.

Now the player can tap a button in new_scene which signals the function to remove the scene, so _remove_scene() would be:

new_scene_margin_container.remove_child(new_scene)

When I run this code in the _remove_scene function I see the child count = 1 before I call “remove_child” and then = 0 after I call “remove_child”:

_new_scene_margin_container.get_child_count()

Okay, so success with removing the child (new_scene) from the tree. However, it is my understanding the scene, in this case “new_scene” still exists in memory. It has not be deleted, just removed from the tree. Now, I see how this is convenient in the case I need to call it again, but what if I’m done with the “new_scene?” How to remove it from memory?

I thought queue_free() was the solution, but when I call it:

new_scene_margin_container.queue_free()

I just get a crash. What would be the correct way to call queue_free() in this scenario - or is not even applicable? Thanks.

new_scene.queue_free()

1 Like

Thanks so much for your help. I’m not sure where to place this solution - I added but got several crashes.

I initially thought to add it the new_scene code BEFORE I called the signal “removeNewScene” - but when I did so I got some crashes.

So I think the proper place to add it would be in the parent scene, in this case “main_scene” (the scene where I instantiated the new_scene).

So I’ve tried:

main_scene.get_child(0).queue_free()

which worked (as in the Godot didn’t crash). Does look to be the correct approach for this? Thanks.

For this example, that is correct. It will fail if you have other children in the main scene before you add the new scene.

1 Like

Thank you again for your help. I will try to implement this now in my game!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.