I had to declare some global enums today and I did it as you did (autoload script), but with a slightly different approach: Instead of creating an "Enums" script, I used an "EnemyUtilities" script. In it I've placed some general purpose functions related to the enemies, that may be used by the enemies themselves or other entities. For example, I have a function that defines how the enemies should move, which I also need to call from a separate node that draws a preview of the movement, or a function that returns a different color depending on the enemy type and that is widely used from many places for FX, UI, materials...Hope you find this useful
What is the best way to declare and use global enums?
- Edited
Not sure if this was mentioned already but all enums are global, they are just guarded by class namespaces. There's no need for autoloads i.e. you don't need any objects to access them. If enum is declared in a named class, it will be accessible in all other classes.
xyz Can you give an example for this? Because when I have a file enemy.gd
...
# enemy.gd
class_name Enemy extends Node2D
enum Foo { red, green, blue }
# [...]
...and then try to use the enum Foo from another script I cannot access it.
# another.gd
print(Foo.red)
print(Enemy.Foo.red)
This would only result in errors. Am I missing something here?
Okay I restarted the editor and now the red error is gone and suggestions do indeed work. But once I add another value to the enum and try to print that the error comes back.
You should submit a bug report on the github tracker.
- Edited
DaveTheCoder I just did a quick look, these might be related.
https://github.com/godotengine/godot/issues/49285
https://github.com/godotengine/godot/issues/76383
I'll look again tomorrow.
- Edited
I haven't encountered any funky behaviors so far. It works as expected. Anyway, bugs aside, the point is - enums are global by design.
- Edited
Toxe If they are global shouldn't print(Foo.red) then work?
They are accessible globally but name-wise they are guarded by class namespaces. In other words, you need to use the class name when accessing, but you can do it from anywhere, hence the access is global. In your example Enemy.Foo
is a global enum.
Btw this is analogous with access to static class methods and properties. If you declare something static it becomes globally accessible via class namespace. In 3.x you can have static methods but no static properties. They neatly added this in v 4 so now we can have both, making the old autoload hack pretty much obsolete.
I know this is an old topic but I made a benchmarker that can show you how much faster or slower using various types of variable references are: https://github.com/elvisish/ElvisishBenchmarker
I usually keep enums in the same script for the reason that frequently (every frame) referencing singletons is much slower than a local script reference, but it might not be a big deal if you're only referencing them ocassionally.