How can I run code after `change_scene(...)` finishes loading?

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

I’m changing a level using get_tree().change_scene("res://xxx.tmx") and would like to access the loaded scene after it loads. Since change_scene(...) loads the scene deferred, I can’t immediately run get_node("/root/...") after change_scene(...), and there’s also no option for a callback.

I also can’t edit xxx.tmx directly, as it is generated by an importer (using Tiled Map Editor).

The problem I’m trying to solve at a higher level is that my scene has metadata, such as spawn points, which I need to process in code after the scene is loaded. This means I need the scene to be fully loaded before I run my code, but I can’t find a way to wait for it loading.

:bust_in_silhouette: Reply From: dancaer69

I don’t know if can help in your case but I have two suggestions:

  1. Use a timer and run your code there:
var timer =
timer.one_shot = true

and run your code after.
2. Use an autoloaded file to define a boolean and set it to false.
Then change its value to true when scene finish loading and check if is true where you need to add the code.

I don’t really think either of those solve the problem. 1) creates a race condition on slow machines, and 2) requires that I know when the scene finishes loading, which is the problem I’m actually trying to solve. I can’t attach a script to anything in the scene, because the scene is imported via a Godot plugin and is not editable.

darthdeus | 2021-05-26 18:27

:bust_in_silhouette: Reply From: omggomb

Not sure but overwriting _ready() on the root node of the scene you’re changing to could work? According to the docs the entire tree of the scene should be loaded when the root’s ready function is called. Though I’m not sure if that also goes for resources.

That would work, but the problem is I can’t modify the scene file, as it is imported from a different file format and converted to .tmx, so I can’t just attach a script to its root node, I need to load the scene and then access it after it gets loaded “from the outside”.

darthdeus | 2021-05-26 20:47