How can I wait until the end of a frame to continue a function?

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

My UI adds buttons programmatically, and then attempts to unload them via queue_free() before adding new ones. Problem is, they don’t unload in time to prevent the UI from breaking in an attempt to fit all the buttons (old, invisible, queued-for-deletion buttons and new ones).

The below solves the issue by essentially waiting out the frame, but is definitely not ideal:

yield(get_tree().create_timer(0.001), "timeout")

Is there a way to essentially wait until the next frame tick happens instead?

1 Like
:bust_in_silhouette: Reply From: Mikko

Have you thought sending a signal on button unload? The callback function for the signal would load new button.

:bust_in_silhouette: Reply From: Christoffer Schindel

If I understand your question correctly, you can use remove_child to remove your buttons from your Tree, and thereafter use queue_free to tell the engine to remove them completely when possible

1 Like
:bust_in_silhouette: Reply From: S Arrowsmith

The literal answer to your question is yield(get_tree(), "idle_frame") (SceneTree emits idle_frame “immediately before Node._process is called on every node in the SceneTree.” (SceneTree — Godot Engine (latest) documentation in English). But I strongly suspect the suggestion of just doing remove_child before queue_free is better.

Thanks, this is what I needed!

I had read in other places that remove_child didn’t have much value over queue_free, and I mistakenly took that at face value. In my case both are definitely needed.

Chose this as best answer because it also explains how to wait a frame as well, if I ever end up needing that.

acwr | 2020-12-29 22:27