How do I preload resources correctly from script?

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

If I have some fixed resource like a packed scene, texture, or script that I want my script to use and reference, it seems like preload is the right function to use since. Which resource it’s using should be changing at all. However, preload only seems to accept a string argument which is incredibly fragile. Any sort of file restructuring or renaming is going to break every reference to that resource which could get very painful as a project grows.

Is there a way to reference a resource for preload in a less fragile way? Or am I thinking about it wrong, and should be using a different approach altogether?

I just have experience that makes me antsy to have a bunch of raw strings sitting in the script. It seems like I can’t even define all the paths in centralized file without running afoul of the string constant limitation. This means I’ve even got multiple copies of the same string literal in different files that may need to get fixed up in the future.

Sorry if that’s too general. Any guidance would be greatly appreciated.

I ended up using export vars for the Resources for what I was trying to do, since it turns out that resources passed in that way are, in fact, preloaded.


export var object_scene:PackedScene
export var resource_script:Resource

Though it still bugs me you can’t export const, but I think some sort of immutable type is already in the pipeline.

Beyond that I also went on a fun journey of making a wrapper node type so I could add resources to the auto-loader, while also supporting editing the exports in that resource. That’s a different story…

DarkLordGorblax | 2022-11-07 21:10

:bust_in_silhouette: Reply From: Wakatta


For every preloaded Resource, your application / game will take that much longer to start and you really should do some type of background / splash screen loading if using preload instead of load


For the centralized part learnt early that’s the best option and on Godot Project start have a tool script that loads all of my preloaded info in to a dictionary from a specific folder into a Singleton like this scheme

["file_name"] = "path/to/file_name"

That can be accessed anywhere and don’t have to worry about filename or directory changes


For the raw string path forgettaboutit
Honestly you’re thinking way too much about it and can encrypt your scripts on export or even for yourself by placing them in a CSV or JSONencrypted of course if you like to make the extra complication of your code.


This is not so much as a real answer but more of a fuel to ignite some ideas