Getting a random enum value and also be able to exclude some values

As the post says, in the game I am working on I needed to get a random value of an enumeration but on some cases I needed to exclude some values of the enumeration, so I came up with this small snippet of code that given an enum type and an array of enum excluded values it will return you a random value of the enumeration.

It works with any type of enum you create 😀

If you have a better way to do it _please_ let me know :).

Quick example on how to use it:


One Response to “Getting a random enum value and also be able to exclude some values”

  1. Daro says:

    Another way I found to exclude enum values of a random methods is creating an alternative enum without the element that I don’t want to use. In my case, i’ve 4 directions relative to cardinal points. I already implemented a strategy patter where i’ve to use this class in case of it is needed. By this way, if I came from a previous north direction, next direction should not be south. Then my alternative enum don’t have south option. I used a Dictionary to let know to the real cardinal point what option was choosen. Of course, i have this code that is repeated on other cardinal points i need

    private class GetAValidDirectionInCaseOfNorth : IGetAValidDirection {

    enum CardinalPointFromNorthDirection {
    North = 0,
    West = 1,
    East = 2

    static Dictionary
    cardinalPointFromNorthDirection =
    new Dictionary();

    static GetAValidDirectionInCaseOfNorth() {
    CardinalPointFromNorthDirection.North, CardinalPoint.North);

    CardinalPointFromNorthDirection.West, CardinalPoint.West);

    CardinalPointFromNorthDirection.East, CardinalPoint.East);

    public void GetAValidDirection() {
    cardinalPoint = cardinalPointFromNorthDirection[
    (CardinalPointFromNorthDirection)Random.Range(0, 3)