Can't intance a scene after returning from a thread

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

I’m not sure what I’m doing wrong, but I have something like this:

var thread

func game():
    loading_scene = loadinganimation.instance()
    add_child(loadinganimation)
    loading_scene.get_node("AnimationPlayer").play("loading")
    thread.start(self, "heavy algorithm that emits finished when it's done")
    yield(self, "finished")
    #print("got past yield")
    loading_scene.queue_free()
    game_scene = game.instance()
    add_child(game_scene)

func _exit_tree():
    thread.wait_to_finish()

The thing that I don’t understand is that the game scene never loads. If I uncomment the print line, it prints, so I know it’s not hanging at yield. If I directly call the function which I’m running on a separate thread, it runs (but causes the loading animation to freeze, which is why I’m taking it off the main thread to start with, it’s quite a heavy algorithm). Putting thread.waittofinish after the yield line also does not do anything.

Why is running a function in another thread caused me to be unable to instance anything when I get back to the main thread?

:bust_in_silhouette: Reply From: psear

So, I found out what the issue was. For some unknown reason (any explanation is welcome), I had to use call_deferred to add the child, rather than calling it directly. I’m not sure why this small difference was so game-breaking, but there you go.

https://www.youtube.com/watch?v=4xMaq-qVQGY

rakkarage | 2020-06-20 20:23