How to use constants from autoloads?

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

I have two files in my project.

  1. which is autoload.
  2. which is reference (not autoload).

extends Node

const WEAPON_TYPE_SWORD = "Sword"
const WEAPON_TYPE_SPEAR = "Spear"

class_name CharacterConstants
extends Reference

     GameConstants.WEAPON_TYPE_SWORD: 0.2,
     GameConstants.WEAPON_TYPE_SPEAR: 0.1

If I run the editor I have error:

  • Error: invalid index “WEAPON_TYPE_SWORD” in constant expression

If I add new line to and save the file then everything is fine. And the game runs in both situations without any error. Why I have this error? Is it possible to disable them?

I found something similar.
Singleton's cannot be used as const in a module · Issue #44837 · godotengine/godot · GitHub
Now I know why :slight_smile:

matdlu | 2023-02-19 19:31

:bust_in_silhouette: Reply From: Inces

autoload is only useful for non-constant variables, that You want to change and keep those changes when replacing whole scene trees.
If You want a place to keep variables, that are always constant, never changed while project is running - use one or few class scripts extending a node - just like your charactercontants class. This class is now loaded BEFORE project is running, which means BEFORE autoload script is loaded. So You can’t expect this class to refer to autoload without errors.

Thanks. Do you know when Reference is loaded? I changed my constants classes extends to Reference and now it is working fine as well. Is there any class/objects/autoload lifecycle (I don’t know how to name it) documentation?

matdlu | 2023-02-19 20:42

I don’t really know it from documenation, but it is kind of intuitive. Classes are loaded with all built-in features of Godot, whenever editor is running. All scripts exist, they have their code, but this code is not resolved, no signals received, they are not rooted to scene tree. But You can call their code in the editor, by using tool keyname script. Another keywords const and enumexpose variables, so they can be easily referred and autocompleted in other scripts. There is also static keyword, that exposes a whole function for this purposes. Thanks to this, You can make const variables by combinations of other consts, enums and static functions. And all of this happens before project is even run. Only after You run project, a scene tree and autoload are created, and all scenes are childed to the tree emitting their ready signals.

Inces | 2023-02-19 21:50