How to properly loop through enumerations

I created a enum and added entries. if I loop through them using “ForEach myEnum” node in a blueprint, some of the enum values will come out as none. Converting the byte to int, the values range from 0 to 1 minus the number of entries. I then notice that the some of the enum values are outside that range.

Is this the correct behavior I should expect?

How should I loop through my enumerations and have all the values come out correct?

An enumeration is just a series of integers. There is no guarantee that those series of integers will be in sequential order – in fact, don’t ever count on that! enums can often be used for bitmask flags. Enums are really just a more “people friendly” way to associate meaning to numbers.

Here’s a good example:

Enum CoinValue
{
Penny = 1,
Nickle = 5,
Dime = 10,
Quarter = 25,
HalfDollar = 50,
Dollar = 100
};

Within UE4, all enum values are going to be unsigned integers with 8 bits, so the range of values is 0 → 255.

As far as looping through the enums, I’d continue using the foreach enum node as you’re doing. Just be aware that enum values won’t be guaranteed to be sequential. You can also cast an enum value to an integer value. I’m not sure what happens to a existing enum byte values when you delete an enum from the list – I think the byte values stay the same? And then adding a new enum continues where the last value left off? I’d have to test this more (I personally use C++ enums).

Since I searched for it myself and found a good solution in the UE4 code I post my solution here. Even if this thread is old.

const UEnum* hardwareInfoEnum = StaticEnum<EHardwareInfo>();

	for (int32 i = 0; i < hardwareInfoEnum->NumEnums() - 1; i++){
		UE_LOG(LogTemp, Warning, TEXT("A: %s"), *hardwareInfoEnum->GetDisplayNameTextByIndex(i).ToString());
	}
3 Likes

Thanks - works like a charm!

Liked ben ui’s examples for looping through enums:
Add a hidden Count enum value as your last enum, and add an ENUM RANGE macro right after your enum declaration:

UENUM()
enum class EAnimal : uint8
{
	Dog,
	Narwahl,
	Count UMETA(Hidden)
};
ENUM_RANGE_BY_COUNT(EAnimal, EAnimal::Count);

Then you can use a for loop with your enum:

for (EAnimal Animal : TEnumRange<EAnimal>())
{

}


I’m used to do that in BP, works well :slight_smile:

1 Like