More info on Enums

Just looking for more info on enums. I have a situation I think they would be useful, or maybe not.

let’s say I have a “RaceManager” script. Inside that script is my enum

public enum GameMode
{
    QuickRace,
    TimeAttack,
    Tour
}

now in my RaceManager script. When the level loads, it should load specific settings or UI based upon the enum selection.

let’s say a event or action fires when the level loads, and checks the enum value. I know you can do if statements or switches like so

    private void SetRaceType()
    {
        if(gameType is GameMode.QuickRace)
        {
            //do something
        }

        else if (gameType is GameMode.TimeAttack)
        {
            //do something else
        }

        else if( gameType is GameMode.Tour)
        {
            //Do this instead
        }
    }

    public void SwitchRaceType()
    {
        switch(gameType)
        {
            case GameMode.QuickRace:
                //do something
                    break;

            case GameMode.TimeAttack:
                //do something else
                break;

            case GameMode.Tour:
                //Do this instead
                break;
        }
    }

but is there a more elegant way of doing this? it’s been a pretty good while since i’ve coded anything and I have seen people mention things like “reflection based” design or something like that. Something that uses a getter setter or something.

Can you imply a function through an enum? like say, if this enum value is called, do this function: without the switch or if statement?

i’ve always used enums in very simplistic ways. I’m open for learning new methods if anyone has any good suggestions or reading material.

In Unity land, enums are dangerous. For a use like above, ScriptableObjects would be the way I would go.

My standard blurb:

Enums enums are bad in Unity3D if you intend them to be serialized:

It is much better to use ScriptableObjects for many enumerative uses. You can even define additional associated data with each one of them, and drag them into other parts of your game (scenes, prefabs, other ScriptableObjects) however you like. References remain rock solid even if you rename them, reorder them, reorganize them, etc. They are always connected via the meta file GUID.

1 Like