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!");
}
}
}
}
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: