How to use switch with enum?

Hello!

So I’m trying to translate Blueprint code to C++ code. How can I do the switch on enum node in c++? I tried it with switch statement and the enum class, but when I’m trying to declear the enum in the header file, it gives me an error that say: “Unrecognized type ‘EWeapons’ - Type must be a UCLASS, USTRUCT or UENUM”.

Hi Ɛdmm

I will provide a simple example of how to implement an ENUM and switch case.

Header

//Declare enum in global scope
//Add UENUM macro so it can be used with blueprints
UENUM(BlueprintType)
enum EMyEnum
{
	itemOne,
	itemTwo,
	itemThree,
};

UCLASS()
class SOURCETEST426_API ATestActor : public AActor
{
	GENERATED_BODY()
	
private:
	//Private variable to hold enum variable data
	TEnumAsByte<EMyEnum> enumVariable;


public:	
	// Sets default values for this actor's properties
	ATestActor();

protected:
	virtual void BeginPlay() override;

};

Source

#include "TestActor.h"

// Sets default values
ATestActor::ATestActor()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = false;

}


void ATestActor::BeginPlay()
{
	Super::BeginPlay();

	enumVariable = EMyEnum::itemOne;

	switch (enumVariable)
	{
		case EMyEnum::itemOne:
			//Do code
			break; 

		case EMyEnum::itemTwo:
			//Do code
			break;
		case EMyEnum::itemThree:
			//Do code
			break;

		default: break; 
	}
}

If you’re still struggling, please post your code.

Thanks

Alex

5 Likes

I did this and now It works, but can I ask why is it good if we set enumVariable to itemOne?

I think it’s a safety habit to be sure that enumVariable is initialized to a default value

Hi Ɛdmm

Glad you found my answer helpful. Please mark this as the correct answer to help others who have similar issues in the future.

As to your question. That was just a test, you must initialize a variable before you can use it. So I created the variable, I assigned it a value and then I switched on the variable, the assignment can happen anywhere, just as long as it does have an assignment before you use it.

Good luck.

Alex