GDScript Enums Tutorial – Complete Guide

In this tutorial, you’ll be introduced to GDScript enums and we’ll show you how they provide a simplified way of reading your code and articulating your logic. If you are excited about refining your coding skills while making them more engaging and interactive, then you’re in the right place!

What are Enums in GDScript?

Enums, also known as enumerations, are a special type of data that comprise a collection of related values. They’re primarily used to define a variable that can only assign certain discrete integer values throughout the script in GDScript, the scripting language used in the Godot game engine.

Why are Enums Important?

Mastering the use of enums in GDScript does more than just making your code neat and easy to read. It holds significance in:

  • Helping developers avoid mistakes, as enums ensure that variables have one of a few predetermined values.
  • Enhancing code clarity and efficiency, as using the name of the enum values can make your code more understandable and thus, easier to manage.

Let’s take a leap and see how enums work in GDScript step by step. Excited? So are we! As we move forward, remember that the goal is not only to improve your understanding of GDScript, but to help you see the awesome potential that emerges when enumeration is brought into play.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Enums in GDScript

In GDScript, defining an enumeration is quite simple. First, we declare an enum using the ‘enum’ keyword. Next, we list the desired values we wish to include. Let’s consider an example:

enum Week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}

In this case, each weekday is a value in our Week enum. Internally, the values get assigned discrete integer values starting from 0. So Sunday is 0, Monday is 1, and so on.

You can use enum variables in your GDScript code like this:

var day_of_week = Week.Monday

if day_of_week == Week.Tuesday:
    print("It's Tuesday!")

Explicitly Assigning Enums

You’re not restricted to the default integer assignments to values in an enum. GDScript allows you to explicitly assign values to these enum entries:

enum Capitals {London=44, Paris=33, Berlin=49}

Now, London gets assigned with 44, Paris with 33, and Berlin 49. You can access these assigned enum values as shown:

var current_city = Capitals.London
print(current_city)

The code above will output 44, which is the value assigned to London in the ‘Capitals’ enumeration.

Updating Enum Values

Another advantage of enums in GDScript is that it allows enums to be updated dynamically within the script, which makes your logic flexible. You can replace an enum’s values as needed:

enum Fruits {Apple, Banana, Cherry}
Fruits = {Peach : 3, Plum : 4, Pear : 5}

# Now if you print Banana, it will return an error
print(Fruits.Pear)  # It will return 5

Keep in mind that once you reassign the values in an enumeration, the old ones are completely replaced.

Remember, coding is all about problem-solving, and enums serve as another powerful tool in your toolbox.

Enums with Strings

In GDScript, enum values aren’t limited to integers. Enum keys can be associated with string values as well:

enum Direction {"North", "South", "East", "West"}

You can access the string values in a similar way to integer-based enums. If you were to print the value associated with North:

print(Direction.North)

This would output “North”.

Enums as Function Parameters

Enums can be notably useful when they are passed as function parameters. This way, it is very clear which values a function accepts:

enum Status {Running, Stopped}

func set_status(status : Status):
    match status:
        Status.Running:
            print("The system is running.")
        Status.Stopped:
            print("The system is stopped.")

This function checks the input status and prints a message based on the provided enum value:

set_status(Status.Running)

Will output: “The system is running”.

Enums Within Classes

In GDScript, just like variables and functions, enums can also be defined inside classes:

class Player:
    enum State {Idle, Walking, Running, Jumping}

    var current_state = State.Idle

    func print_state():
        match current_state:
            State.Idle:
                print("The player is idle.")
            State.Walking:
                print("The player is walking.")
            State.Running:
                print("The player is running.")
            State.Jumping:
                print("The player is jumping.")

In these examples, the enum values (like `State.Idle`) directly reference a constant static variable within the class, providing an easy and secure way to access these static values.

Nested Enums

You can also nest enums inside another enum. This can help group related constants together, providing better code readability and organization:

enum UI { 
    enum Color {Red, Green, Blue}, 
    enum Screen {Start, Main, End}
}

Accessing a nested enum works similarly to accessing regular enums:

print(UI.Color.Red)
print(UI.Screen.Start)

The result will be the numeric representation of the enum values (0 for Red and 0 for Start, as both are the first elements in their respective enums).

Enums can greatly augment your GDScript coding experience with their versatility and the simplicity they bring to your code structure. Embrace enums and level up your Godot scripting gameplay!

Enums with Arrays and Dictionaries

In more complex scenarios, enum entries could represent arrays or dictionaries. Let’s take a look at how this works:

enum ArrayEnum {[1, 2, 3], [4, 5, 6], [7, 8, 9]}
enum DictEnum {{'key': 'value'}, {'another_key': 'another_value'}}

Both these examples show how you can utilise complex data structures within your enums:

print(ArrayEnum[1])  # It will print the array [4, 5, 6]
print(DictEnum[0])   # It will print the dictionary {'key':'value'}

Custom Initialization of Enums

Enum values in GDScript are generally initialized in sequence from zero, but you are free to assign your own values. This can be useful for mapping your enums to specific meanings or other systems:

enum Days {Sunday = 7, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6}

Now Sunday is represented by 7 and the rest of the days follow:

print(Days.Sunday) # Output: 7
print(Days.Friday) # Output: 5

Enum Type Validation

The type validation benefits of enums are not to be ignored. When your variables should only have one of a few distinct values, enums can help ensure your code runs as expected:

enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
var today = Days.Monday

# This will cause an error, "Saturday" is not a valid enum value
today = "Saturday"

Using names instead of arbitrary integers also improves code readability and can reduce mistakes.

Enums and Switch Statements

Enums are particularly handy when combined with switch statements. For example, you could define gameplay states and elegantly switch between them using an enum:

enum State {IDLE, WALKING, RUNNING, JUMPING}

var current_state = State.IDLE

match current_state:
  State.IDLE:
    print("Standing Still")
  State.WALKING:
    print("Walking")
  State.RUNNING:
    print("Running")
  State.JUMPING:
    print("Jumping")

Here the `match` statement, similar to a `switch` statement in other languages, is combined with enum to handle different game states. Changing the `current_state` variable would result in different outputs.

Conclusion

Enums are an incredibly powerful construct in GDScript, offering ways to define specific, valid values for your variables. Using enums can make your game code more readable, maintainable, and overall safer. Ensuring correct code behavior by coding smart is one step towards becoming a more adept game developer. Seize the power of enums and make your GDScript code shine! Happy learning!

Where to Go Next?

Your journey in game development is a thrilling one, and you’re just getting started! Utilizing GDScript enums is a step forward, but there’s so much more to discover. To keep soaring, we highly recommend checking out our Godot Game Development Mini-Degree.

This comprehensive program covers a wide spectrum of game development topics, from using 2D and 3D assets, GDScript, gameplay control flow, to player and enemy combat. You’ll also delve into diverse game mechanics like RPG, RTS, survival, and platformer genres. The courses are suitable for beginners and more advanced developers alike.

Our courses are designed to be flexible, accessible 24/7 and provide step-by-step guidance to create real game projects. Plus, the Godot 4 engine you’ll be using is lightweight, powerful, and easy to learn.

At Zenva, we offer over 250 supported courses to take your programming and game development skills to new frontiers. We offer coding courses for everyone, from absolute beginner to seasoned professional. Our aim is to make learning accessible, engaging and beneficial for your future.

To broaden your options, feel free to explore our collection of Godot Courses. These offer a range of subject areas to strengthen your skills in different areas of Godot game development.

Take the next step. Your path from beginner to professional awaits. Happy Programming!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.