Long algorithm causes loading scene to hang

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

I’ve been struggling for a while with setting up a loading screen for when the game is running a somewhat heavy algorithm. I know that this algorithm can take upwards of 10 seconds, and I decided to put a loading screen there.

It’s something like this:

var loading = preload("path to loading scene")

func game():
    loading_scene = loading.instance
    add_child(loading_scene)
    #loading_scene.get_node("AnimationPlayer").play("loading")
    #yield(get_tree().create_timer(0.5), "timeout")
    heavy_algorithm()
    loading_scene.queue_free()
    run_game()

As it is now, the loading will happen without the loading screen ever appearing. If I uncomment the yield line, the loading screen appears. I think what is happening here is the scene is only updated once the script completes, unless there is some sort of break (yield) mid way.

This workaround, though not ideal, should have worked, if not for the fact that it will also interrupt any animation. My loading screen consists of a rotating icon, if I uncomment the animation line, the animation will play for the time it takes for yield to finish. When it hits the algorithm, the animation freezes. The game progresses as normal once the algorithm completes, but I have no idea how I can just have the loading animation play while an algorithm is occurring in the background.

:bust_in_silhouette: Reply From: rustyStriker

Not sure about how well it will work, but do the heavy calculation on a different thread, not on the main one, that way you can do a lot of calculations without affecting the main loop too much

Threading in Godot:
https://docs.godotengine.org/en/stable/tutorials/threads/index.html