+3 votes

I want to have a constants file that has a bunch of enums, ints, vectors, and preloads that I can use in all gdscript files. If I want to export some of these enums, the only way I know is to preload this constants file in all the scripts, which seems pretty inconvenient and potentially redundant loading (not sure if preload is handled intelligently across different gdscript files). Is there an equivalent of python import or C++ #include in gdscript?

imagine the following scenario:

# constants.gd
enum Spell = { FIRE, WATER, WIND EARTH }; enum Item = { CONSUMABLE, WEAPON, ARMOR, KEYITEM }; enum Obj = { BUILDING, NPC, OTHER };

# spell.gd
const constants = preload("res://constants.gd"); export (constants.Spell) var Type;

# item.gd
const constants = preload("res://constants.gd"); export (constants.Item) var Type;

# obj.gd
const constants = preload("res://constants.gd"); export (constants.Obj) var Type;

I'm not sure if calling preload() on the same resource will consume more memory, imagine hundreds or thousands of obj/item/spell classes. Is there is a better way at handling this situation. I think it's a very common practice to have a separate constants file. But in practice, it's much trickier than it should be.

Perhaps we can take AutoLoad to the next level with AutoPreload in the next version?

in Engine by (17 points)

For my project, I have another global variables gd file (let's call it globals.gd) that contains non-constants.

All my classes potentially need access to both constants.gd and globals.gd.
globals.gd makes reference to constants.gd
This creates dangerous cyclic references. What is the best way to handle multi-layered inclusion (inheritance)?

Each Resource is preloaded only once so multiple preloads will not consume extra memory.

I would say that the way things are is ok, but not ideal. The AutoPreload is just an idea since we have AutoLoads. I think having something like AutoPreload (if it's not too technically consuming) will resolve this more gracefully.

1 Answer

0 votes

You can simply autoload your constants.gd file and call it from anywhere like that:

var mySpell: int = Constants.spell

Your constants.gd file can look like that:


const spell: int = 100

To add constants.gd file, go to project settings and click "AutoLoad" tab:


And find and add your constants.gd file from "Path" input.

See docs: https://docs.godotengine.org/en/latest/tutorials/scripting/singletons_autoload.html

by (58 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.