I bet most of you already knows what Enums are. To be short, Enums are basically list of integers in a form of a text, so they are very easy to read and understand. Enumerated types are incredibly useful for code documentation and readability purposes when you need to represent a specific, predefined set of states. To get more detailed explanation about enums,  you can go here.


We are going to create an enum class and give it some values we can use later. We set it the way, we can edit it in Blueprints also. Finally we give one of our enum class values to it and use Switch case to check out what value was given. We start by creating our enum. Enums are declared just over the UCLASS() macro. We give three values to our enum called ”First”, ”Second” and ”Third”. UMETA will allow us to customize the name we are seeing in Blueprints. We give slightly different name just to see the effect.

UENUM(BlueprintType) // "BlueprintType" is essential to include
enum class MyEnum : uint8
First UMETA(DisplayName = "First One"),
Second UMETA(DisplayName = "Second One"),
Third UMETA(DisplayName = "Third One")

Now that we have created the enum class. Lets create a object from it. We do that in protected section this time.

// Called when the game starts or when spawned
virtual void BeginPlay() override;
MyEnum EnumToUse;

We are ready to use our enum inside .CPP. In BeginPlay() we do a little test, just for fun. First we set the enum to be some value. Then we use switch case to print different things depending what the enum value was.

// We set enum to be one of the values we set it to have. Normally, this would change depenging what happens inside your game. Example, if you change weapon, enum could keep track of the ammo type your player shoots. 
EnumToUse = MyEnum::First; 
// Switch case different possibilities. In real scenario, your weapon could spawn different class depending the enum.
switch (EnumToUse) 
case MyEnum::First:
UE_LOG(LogTemp, Warning, TEXT("First enum selected"));
case MyEnum::Second:
UE_LOG(LogTemp, Warning, TEXT("Second enum selected"));
case MyEnum::Third:
UE_LOG(LogTemp, Warning, TEXT("Third enum selected"));
UE_LOG(LogTemp, Warning, TEXT("Unknown value"));


SO lets start our game and check the logs. We see our changes there! Because our enum is blueprintType, we can use it in blueprints. It is very handy when looking it visually.

If we don’t need to use enums in blueprints, we can use the C++ 11 feature and just create enum inside the scope. Inside header file.

// We declare enum that has some values we specify
enum class Color { Red, Yellow, Green, Purple };
Color ColorEnumObject;

In .CPP we can use it very easily

if (ColorEnumObject == Color::Red)
  UE_LOG(LogTemp, Warning, TEXT("Color is red!"));

And that’s it! Now you know how to use enums inside Unreal Engine C++!


Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *