random enum out off a list (or array) of some specific enums

Hello everyone,
I know I can get a random enum of a specific range of enums. For example (Difficulty is the enum):
currentDifficulty = (Difficulty)Random.Range(0, 3);
Now I want to get a random enum of some sort of a list (or array) of specific enums (not all enums and not a range). For example: I want to get a random enum off this array of enumA, enumC, enumD, enumE, enumR and enumT. How do I approach that?

Thanks in advance!

For individual choices, something like this should work:

T PickRandom<T>(IList<T> options)
{
   int index = Random.Range(0, options.Count);
   return options[index];
}

For multiple unique (non-repeating) choices, what I usually do is copy the list and shuffle it, then take however many.

1 Like

Thank you @Errorsatz for the quick answer! Unfortunately I don’t understand your example completely (especially line 1). Where would I put the enums? At options? Thank you very much :slight_smile:

Yeah, you’d pass the array of enums to options. So something like:

public enum Flavor { Plain, Barbecue, Strawberry };
public Flavor[] flavorOptions;

void Start ()
{
    Flavor chosen = PickRandom(flavorOptions);
    Debug.Log("Selected flavor = " + chosen);
}

The function above will throw an IndexOutOfBounds exception if you give it an empty array, incidentally. You could add a check to throw a more specific error or return a default value.

1 Like

Thank you @Errorsatz ! Now I got it and it´s working :slight_smile: