Preload with variable argument

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jospic
:warning: Old Version Published before Godot 3 was released.

Hi,
I need to instance scene through preload command, but its argument must be a variable.
Preload accepts only string constant…
Any suggestion?
Thanks in advance
-j

:bust_in_silhouette: Reply From: Vladislav Vorobiev

Preload is executed at script compile-time, there are no way you can use non-constant string, use load instead.

What does it mean to be executed at script compile-time? I thought compiling is what creates the final executable.

avencherus | 2016-08-11 03:49

I don’t really know how it’s done, but it seems it works that way: when scene is loading, all it’s resources being loaded too (stuff like textures, other scenes used in currently loading scene and finally scripts). Godot exactly knows what to load because you created all the scenes and other nodes like Sprite in Godot Editor and Godot can save this data into scene. Finally, when scripts are loaded, they are parsed, and then compiled in byte-code for faster execution. When script parser sees call to ‘preload’, it can call ResourceLoader to load resource, specified as string in your ‘preload’ call. In that case, scene starts only when all resources are loaded.

But when you call ‘load’, you send message to ResourceLoader to load specified resource while your scene is already playing, which means your game will freeze (or maybe just script will freeze) until resource loads completely.

So basically advantage of compile-time resource loading is that you avoid freezes during gameplay, but scene loads for a longer time. When you use dynamic loading of resources, you save some memory and load stuff you need only when you actually need it. You can even fix freezes in scene by using something like ResourceInteractiveLoader, see http://docs.godotengine.org/en/latest/tutorials/engine/background_loading.html

Vladislav Vorobiev | 2016-08-11 07:56