_ready() without blocking main thread

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

I tried to add a loading screen to scene transitions since some scenes started taking too long to load. However, it turns out that the time-consuming part was not loading a PackedScene, but initializing the instance and all its children through their _ready() functions.

I’m having this issue where add_child() freezes the main thread, and therefore causes the loading animation to either freeze or not appear at all. How do I initialize this new Node without causing the main thread to freeze?

:bust_in_silhouette: Reply From: omggomb

Why is it freezing? Are you doing expensive calculations in your ready functions, or are you just adding a ton of renderable objects to the scene?

If you’re adding many visible objects at once it will take some time to add them to GPU memory. You could try setting every object’s visibilty to false and then loop over them to unhide them while yielding a frame. Something like this:

func _set_visible_lean(root: Spatial):

	for c in root.get_children():
		_set_visible_lean(c) # Recurse down tree first

		c.visible = true # When at the bottom, start unhiding

		yield(get_tree(), "idle_frame") # Wait a frame to allow the animation to update
		
	root.visible = true # Don't forget so unhide parent