#Enums

7 messages · Page 1 of 1 (latest)

radiant tartan
#

Could someone explain to be where / when an enum is usefull? From what understand, you could just use a string instead. For example:
this:

extends Node2D
class_name Card2D
# //types: sun, moon, sword, sheild
enum suits {
  SUN,
  MOON,
  SWORD,
  SHEILD
}

@export var suit = suits

func _ready():
  if suit == suits.SWORD:
    $Sprite.Texture = "res://sword.png"
  elif suit == suits.SHEILD:
    etc...

can also be writen as:

extends Node2D
class_name Card2D
# //types: sun, moon, sword, sheild

@export var suit: string

func _ready():
  if suit == 'sword':
    $Sprite.Texture = "res://sword.png"
  elif suit == 'sheild':
    etc...

because in both examples, if I want to change "sun"/suits.SUN to "star"/suits.STAR, I still need to go through all occurences of it in my code.
Whats the point of using it?
The only benifit I see is that you have a dropdown in the inspector instead of typing out the string. Could someone pls enlighten me?
thanks!!

sand finch
#

personally a dropdown is enough for me to do it, but i think an enum is more efficient to compare. since to a computer a string is more complicated than an enum which is a more rigid data type.

slender blade
#

also, less error prone, since you exclude the chance of a typo

queen fog
#

you can also get the best of both world with export_enum :

@export_enum("sun", "moon", "sword", "shield") var suit: String = "sun"

As you get a dropdown in the editor, it's less error prone and you don't have to declare an enum

livid orbit
#

In this example, I personally would use strings and use a format function to insert the file name (sword, shield, etc) into the rest of the path. One case I personally use enums is when there is an array or dictionary underlying an object's data and predefined indexes or keys are needed for set/get. I read somewhere that enums are best used sparingly. There is a term called "enum forest" when someone really likes to use a lot of them 😆

copper carbon
#

its mostly used as a more descriptive alias that you cant accidently misspell because you are comparing hard coded strings

radiant tartan
#

Ok that answers it. Thanks guys!!