Menu
CoddyTech

Defining an Enum

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 38 of 78.

An enum declaration is the keyword enum, a name and the options inside curly braces, separated by commas. The Godot style guide writes the name in PascalCase and the options in CONSTANT_CASE:

enum Direction { NORTH, EAST, SOUTH, WEST }

A long enum can put one option per line. A comma after the last option is allowed:

enum Weapon {
	SWORD,
	BOW,
	STAFF,
}

You can choose the value of an option with =. An option without a value gets the value of the option before it plus 1:

enum Difficulty { EASY = 1, NORMAL, HARD, NIGHTMARE = 10 }
# EASY = 1, NORMAL = 2, HARD = 3, NIGHTMARE = 10

The enum is also a type. A variable declared with it holds one of its options:

var level: Difficulty = Difficulty.HARD
print(level) # 3
print(level * 50) # 150

A script can declare several enums, each with its own name. If you leave the name out, as in enum { LEFT, RIGHT }, the options become constants of the script, and you write LEFT without a prefix.

challenge icon

Challenge

Easy

The program reads the base damage of an enemy (a whole number). On harder difficulties the enemy hits harder: the damage is the base damage times the value of the difficulty.

  1. At the top level of the script, declare an enum named Difficulty with the options EASY (value 1), NORMAL, HARD and NIGHTMARE (value 10). Give NORMAL and HARD no value of their own, so they count on from EASY.
  2. Print the damage for each difficulty, one per line, using the enum options in the calculation.

For the input 12, the output is:

EASY: 12
NORMAL: 24
HARD: 36
NIGHTMARE: 120

Try it yourself

extends Node

# Declare the Difficulty enum here

func _ready():
	var base_damage := int(OS.read_string_from_stdin())
	# Print the damage for each difficulty
	pass
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler