Getting a Enum value after comparing string name

I am trying to get a value in a enum after i compare the list of names in the enum with another string.
Here is my code, is there any other way i can do this please? thank you for your time.

public class Test {
   
 enum levelList { StartLevel = 1, level2 = 2, level3 = 3, level4 = 4, level5 = 5 }

    void Start() {

        string sName = SceneManager.GetActiveScene().name;

        foreach (string emn in Enum.GetNames(typeof(levelList)))
        {
            // Debug.Log(":: " + emn );

            if (emn == sName)
            {
                //Get the value of emn in levelList
            }
            else
            {
                Debug.Log(" Not found!");
            }

        }
        
    }
}

Why do you even work with strings. Just use

string sName = SceneManager.GetActiveScene().name;

levelList level = (levelList)System.Enum.Parse(typeof(levelList), sName);

Though if you really perfer using strings, the resulting array that “GetNames” returns corresponds to the array returned by GetValues. So for example the name “level2” would be index 1 inside the names array and the value in the values array at index 1 would be “2”.

GetValues returns an “Array” as the underlying type of an enum can be different. By default it should be “int”.

edit
Note that Enum.Parse will throw an exception if the passed string doesn’t exist in the provided enum type. Unfortunately Enum.TryParse has been introduced in .NET 4.0 and thus is not available in Unity. Though you can write your own version:

public static bool TryParseEnum<TEnum>(string aName, out TEnum aValue) where TEnum : struct
{
    try
    {
        aValue = (TEnum)System.Enum.Parse(typeof(TEnum), aName);
        return true;
    }
    catch
    {
        aValue = default(TEnum);
        return false;
    }
}

And use it like this:

levelList level;
if (TryParseEnum<levelList>(aName, out level))
{
    // parsing successful
}
else
{
    // parsing failed
}

Thank you guys :slight_smile: