Search code examples
c#unity-game-engineenums

New to C#, can anyone explain to me how enums and setting variables for enums works?


I'm sure this is a very simple question, but I'm learning how to program in C# and the "flow" of this text adventure program makes perfect sense to me, but I'm confused how the third line "private States myState;" works.

As you can see, the program starts by setting the variable myState to States.cell, which calls a void method (not shown below) that waits for a key that changes the variable "myState" thus updating the update function.

My question is, how does the "enum" class work? It seems as though it's possible to make a variable from the "enum States" line, but I don't understand why that is. Sorry if this is a really stupid question.

Here's the code:

public Text text;
private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};
private States myState;

// Use this for initialization
void Start () {
    myState = States.cell;
}

// Update is called once per frame
void Update () {
    print (myState);
        if      (myState == States.cell){           state_cell();} 
        else if (myState == States.sheets_0){       state_sheets_0();} 
        else if (myState == States.mirror){         state_mirror();} 
        else if (myState == States.lock_0){         state_lock_0();} 
        else if (myState == States.sheets_1){       state_sheets_1();}
        else if (myState == States.cell_mirror){    state_cell_mirror();}
        else if (myState == States.lock_1){         state_lock_1();}
        else if (myState == States.freedom){        state_freedom();}
}

Solution

  • An enum is basically a special type that lets you define named values. You're creating a named type just as you would if you were defining a class. What your code is actually doing is first defining your enumerated type called States with all the possible named values, then declaring a variable "myState" using the enum type "States" that you defined in the line before. What you can't see in your code is that by default in c# the underlying type for your enum is an integer, and each of your possible values also has an integer value assigned to it which could be overridden if needed, so all you're really doing in your update code is an integer comparison. Is there any reason you're not using a switch instead of that big if/else block? Also you could eliminate the start function and just instantiate your myState variable like this:

    private States myState = States.cell;
    

    MSDN has pretty good documentation for it here:

    https://msdn.microsoft.com/en-us/library/sbbt4032.aspx