Is there a way to use numbers for enums?

Okay, the point of using an enum is to have understandable designations for these variables, instead of using numbers.

But I want to make a debug script that would systematically test each iteration of an enum I have created. This would require me to create a large switch event with a case for every possible type within that enum. It would be a lot easier if I could supply a number and have it convert that into the enum, and thus test out each iteration with a simple loop.

1 Like
enum Stuff {Alpha, Bravo, Charlie}

void Start () {
    foreach (var stuff in System.Enum.GetValues (typeof(Stuff))) {
        Debug.Log (stuff);
    }
}

–Eric

1 Like

Eric’s answer is correct. The reason this works as that internally, enums are stored as integers, anyway.

This code:

enum Stuff {
     Alpha,
     Bravo,
     Charlie,
}

is syntactically equivalent to

enum Stuff {
     Alpha = 0,
     Bravo = 1,
     Charlie = 2,
}

enums are a very handy data structure, and important to learn more about:

Well, technically, the reason it works is because it’s iterating over a collection. It doesn’t matter if they’re numbers or not, although basically they are, of course. Also it doesn’t matter if the enums are numbered consecutively. You can iterate over the enum as a string array with GetNames:

enum Stuff {Alpha = 5, Bravo = 8, Charlie = 12}

void Start () {
    foreach (var stuff in System.Enum.GetNames (typeof(Stuff))) {
        Debug.Log (stuff);
    }
    foreach (var stuff in System.Enum.GetValues (typeof(Stuff))) {
        Debug.Log ((int)stuff);
    }
}

–Eric

1 Like

I know that enums are numbers, but that still doesn’t mean I can pass an integer to a function that asks for an enum.
What I didn’t know about was the option to return those names with System.Enum.GetNames as demonstrated above.
Thanks for the solution!

And, for future reference, your example would work with a cast!
Assuming Eric’s above definition for stuff:

//In the case of a function that takes an Enum
void SomeMethod(Stuff stuff){
     //whatever
};

SomeMethod((Stuff)5); //would send Stuff.Alpha to the function