system
February 16, 2019, 11:28am
1
Attention
Topic was automatically imported from the old Question2Answer platform.
Asked By
alexzheng
I want to share a named enum type in different scenes.
For example
In SceneA:
export(MyNamedEnum) var type
In SceneB
export(MyNamedEnum) var type
MyNamedEnum is somethings like this:
enum MyNamedEnum {TYPE_1, TYPE_2}
The question is where can I define this MyNamedEnum for global use?
I tried to define it in an autoload node called global, and use it like:
export(global.MyNamedEnum) var type
That doesn’t work.
The parse global.MyNamedEnum can work in instance functions but not in the export definition.
There is no relationship between SceneA and SceneB.
1 Like
system
February 16, 2019, 9:38pm
2
Reply From:
Zylann
It is not possible to declare global enums directly, because any GDScript thing exists within a class (i.e a script for .gd files, that’s the same).
So if you want to re-use the same enum in multiple places, you have to create a script, which contains only that enum:
MyNamedEnum.gd:
enum MyNamedEnum {
TYPE1,
TYPE2
}
And then, use it by “import”:
const MyNamedEnum = preload("path/to/MyNamedEnum.gd")
func _ready():
print(MyNamedEnum.TYPE1)
I dont’t know if that works when used with export
though.
In Godot 3.1, there is a way to almost make it global, by giving a global class name to the script containing the enum:
# At the top of MyNamedEnum.gd
class_name MyNamedEnum
Which means MyNamedEnum
will be available everywhere without the need for preload
. That should work for const
and static func
as well.
The preload method works for export.
The class_name does not.
Thanks.
alexzheng | 2019-02-17 15:49
system
February 3, 2023, 5:27pm
3
Reply From:
salihkallai
Godot 4 solution:
Create a gdscript file like this
class_name Type
enum {
RESOURCE,
FOOD
}
Then you can call it from anywhere like this:
Type.FOOD
I am using Godot v4.0.1.
It works for one enum type.
If you try to create a second gdscript files with a different enum, it prints the error:
Parse Error: Class “Type” hides a global script class.
Also, I can assign the enum values, but declaring the type of a variable or parameter does not work either. In the example above, declaring:
var x:Type = Type.FOOD
This would result in the following error:
Parse Error: Cannot assign a value of type Type. to variable “x” with specified type Type.
fabioamc | 2023-04-10 20:48
2 Likes
system
April 17, 2023, 11:21pm
4
Reply From:
Ethergeist
A Modified Godot 4 Solution
Constants.gd
class_name Constants
enum PlayerTypes {
LOCAL,
REMOTE
}
Then to use this with another class and define a type
class_name Player
extends CharacterBody3D
@export var type: Constants.PlayerType = Constants.PlayerType.LOCAL
...
The variable exported to the editor will be a drop down list with the values in the PlayerType enum. Seems to work in any gdscript file without having to use preload.
8 Likes