+2 votes

I have a resource preloaded in my main script, and finding no way to access that PackedScene from children nodes, I was wondering if creating a variable to preload a resource in every scene that needs to instance it is a big issue or if there's some better way to optimize.

For example, I have a Character resource scene, packed in the root node. If I have a sub-node that is character creation, i want to utilize that same packed scene to instance in that child node. Or am I thinking about this all wrong?

in Engine by (22 points)

2 Answers

+3 votes
Best answer

Yes, go ahead and make a preload variable in every file that needs it. Each resource will only be loaded once no matter how many times you preload() it.

It also makes clear what files given script uses.
Godot 3.1 can warn you if there's unused variable so in case your script no longer needs some preloaded PackedScene you will get a warning.

Renaming a resource might be a problem since you'll want to rename all instances of file path. In Godot 3.1 there will be working 'Find in files' option that will be able to perform project-wide replace.

Both of those 3.1 functionalities are already available in 3.1 alpha.

by (2,294 points)
selected by
+2 votes

Well, there are different ways to do it.. The simple way is creating a singleton, the famous "global" node.
Create a GDScript named "global.gd", inside it place the preloaded resource reference.
Then in the project settings go to the "Auto Load" tab and in the "path" select the file you just created (you can search in the load dialog window by clicking in the " .. " button), give it a name and click in the "add" button.
This will add a line at the box showing your new singleton.
If done, now this GDScript is loaded when you play the game and can be acceded from every node in your game by typing the name you gave it. Its a good place to set variables you need in many scenes or functions too.

by (325 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.