Working with Enums in Unity

Working with Enums in Unity is something I continuously want to do, and I continue to forget how this works (since I do not code that often) So, here is a quick guide on how to set it up, and get it working, so that you can create selectable dropdowns.

There is a variation of uses for this, but typically, I will use this if I have to add this script to multiple items in the game, that have to behave slightly different. Some critical voices will probably say that there is better ways to do this, and they are probably right. If you have ideas for this, please comment 😉

Anyhow, here is the code example that shows how this is done.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponUpgrader: MonoBehaviour {
    
    //Here we set the different options that we want in the dropdown
    public enum OptionSelector{ option1, option2, option3}

    //This is the exposed dropdown in the editor
    public OptionSelector selectedOption;

    //This is where we do something depending on what the dropdown was set to
    private string GetNameOfOption(){
        string name;

        if (selectedOption == OptionSelector.option1)
            name = "Option number 1";
        else if (selectedOption == OptionSelector.option2)
            name = "Option number 2";
        else if (selectedOption == OptionSelector.option3)
            name = "Option number 3";
        else
            Debug.LogError("Seems like no option was selected.");

       return name;
    }
}

I hope this will help, if there is any questions that you have to this, please leave a comment.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.