GDScript equivalent to String Enums?

Currently facing the problem of wanting the functionality of enums (so autocomplete, no possibility to misspell, etc.) but with unique identifiers instead of an integer.

Typescript offers string enums for that case, but in Godot as it seems you can’t really change the way enums work. The problem I have is that I want to expand and reorder the values in an enum at a later point, but without all the references then pointing to a wrong enum value.

so:

enum MyEnum {
  SPELL_A, #(0)
  SPELL_B, #(1)
  BUFF_A, #(2)
}

and then later on:

enum MyEnum {
  SPELL_A, #(0)
  SPELL_B, #(1)
  SPELL_C, #(2)
  BUFF_A, #(3)
}

What I want is basically for BUFF_A to keep it’s value, even if I reorder the items in the enum. Is there some other way to achieve the functionality of constrained string values / identifiers, that could solve my problem here? Ideally this can be a dropdown when exported.

1 Like

I think the easiest way to make something like this would be to put it in a separate script, and not make it an enum at all.

So you’d have a script dedicated for this enum, containing

extends Node

const SPELL_A 	= 0
const SPELL_B 	= 1
const SPELL_C 	= 2
const BUFF_A 	= 3

You then add this script as an autoload:


image

And now the editor will auto-complete
image
image

It’s very much a hacky way of doing it, but I am not sure you can replicate string enums in an other way

1 Like

Hey thanks for the idea :slight_smile: That’s actually nice for having autocomplete on strings. I guess at some point this will impact performance, but should be ok for my use case…

Now I would need to figure out how to do @export_enum with this, so the editor shows a convenient dropdown when I want to specify a value of that “fake enum”… :thinking:

1 Like

You can do that by defining the value:

enum MyEnum {
    val1=0, # val1: 0, is also possible
    val2=1,
    other_value=5
}

if you want to export it you can do the following:

@export var my_val: MyEnum

Note that changing the values inside the enum might take a while to update in the inspector

4 Likes

Ah I see, thanks so much!

1 Like

post like these should be inside the “help”-category

1 Like

Yes, I realised after posting that the wrong category was selected. As far as I know I can’t change the category afterwards. Sry!

1 Like

i think you can still change the category when you press on the pen next to the title