Preload() from a dictionary

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

Is this possible?

Every time I try something like:

dir = [
     "resource" : ["res://PathToWhatINeed", "res://AnotherPath", "res://YetAnotherPath"]
]

func _ready():
     var grab_bag = dir[resource] 
     var item1 = preload(grab_bag[0])

I get an error that preload is expecting a string. I checked out the docs and preload looks like its a static type. So it MUST only have a string path in it. Is this correct?

If so, what is a better way I can use a dictionary and a single key to preload multiple scenes into variables?

:bust_in_silhouette: Reply From: Ertain

Have you tried something like this?

dir = { "resource" : ["res://PathToWhatINeed", "res://AnotherPath", "res://YetAnotherPath"] }

func _ready():
     var grab_bag = dir["resource"] 
     var item1 = preload(grab_bag[0]) # Also try 1 or 2.

Hey, thanks for catching my typo. I changed it in the original question. I did have it as var item1 = preload(grab_bag[0]) originally, but I think I did a ctrl - v in the wrong place.

So to answer your question, yes I’ve had it structured like that, but it seems preload, really wants a string. The error comes up in editor, so it’s not during compiling the game. It simply wants a hard in quotations “” string. Or so it seems anyways.

Dumuz | 2020-08-20 23:38

:bust_in_silhouette: Reply From: Dumuz

Found the answer here:

forums

Akien answers it, saying:

As the message said, preload expects a constant string argument. That’s because preload is run when you start your project and preloads all the listed resources in the memory.

In your case, since you are building the string at runtime based on other variables, it can’t be consider a constant (const), so you need to use load instead of preload to load the resource in memory only when called for.

:bust_in_silhouette: Reply From: Chevon

Try this but im not sure

dir = { "resource" : ["res://PathToWhatINeed", "res://AnotherPath", "res://YetAnotherPath"] }

func _ready():
     var grab_bag = dir["resource"] 
     var item1 = preload(str(grab_bag[0]))