Trouble generating random enum

I have an enum to track character hair color, and I’m trying to set it to a random value. I tried doing it by casting a random uint8 as the enum in question:

//.h
UENUM(BlueprintType)
enum class EHairColor : uint8{
		Black,
		Brown,
		Blonde,
		Red,
		Dyed,
};

//.cpp
 EHairColor hair;
	uint8 randomSeed;
	randomSeed = FMath::RandRange(0,2);
	hair = Cast<EHairColor>(randomSeed);

This produces a compiler error, “None of the two overloads could convert all the argument types,” which I assume means that you can’t cast an integer into an enumeration that way- is there a preferred method for getting random enums?

Hmm, that eliminates the casting error I was getting, but it produces a new one, “illegal qualified name in member declaration”

Double reply, but I found that removing “::Type” entirely makes it compile! Thank you very much :slight_smile:

have you tried Static_Cast?

 //.h
 UENUM(BlueprintType)
namespace EHairColor 
{
	enum Type
	{
         Black,
         Brown,
         Blonde,
         Red,
         Dyed,
	};
}

//.cpp
	EHairColor::Type HairColor = static_cast<EHairColor::Type>( FMath::RandRange(0,2) );

Sorry for the multiple comments, but I added this for all the enums I’m randomizing, and it doesn’t look like it works: it compiles and runs cleanly, and it returns different results for each character, but it returns the same results every time- if a character is generated with blonde hair and green eyes, they get that pattern every single time. Is that likely down to an eccentricity of Rand?

the reason it didn’t compile with ::Type on the end, is because you are declaring your enum inside a class. you can either declare it outside of a class using the syntax i posted above, or you can put it inside a class and replace the namespace with a struct, but either way, you should use the scoped “::Type” method because it avoids naming conflicts.

from the UE4 coding standards document:

“Note that for locally-declared enums, you will not be able to use a namespace for scoping. In these cases, we opt to declare a local struct with no member variables, only a local enum type and use that struct for scoping.”

RandRange() should produce a random integer every time. to get the same results from a random operation, you should use random stream, which accepts a seed.

Thank you very much for the elaboration! :slight_smile: