Saturday, March 1, 2014

Unity3d Enum - How to loop Enum with foreach in Unity

If you want to iterate through your enum class members in Unity3d with C#,  you can  use a foreach loop.

Infact Enum class does not implement the IEnumerable interface. This means that you cannot directly loop through all of the declared values using the foreach statement.

But Enum provides a static method named as GetValues.

This gives you an array of your enum class fields.

Like say we have a enum of  unity3d  game object names, like this one:


enum UnityGameObjectNames {
myplayer = 1,
myEnemyZombie,
myFriend
}

and you want to use unity3d gameobject names in one of your functions like start or something. You can do this like this:

void Start() {
foreach (UnityGameObjectNames  unityName in UnityGameObjectNames.GetValues(typeof(UnityGameObjectNames)))
    {
Debug.Log(unityName + "  is my Unity3d Object Name");
    }
}

or you can also specify array type, so that there wont be extra boxing - unboxing. Unity also runs on mobile devices so any tiny bit of optimization may be needed.

Better set the type of array like this:

foreach (UnityGameObjectNames  unityName in ((UnityGameObjectNames[]) UnityGameObjectNames.GetValues(typeof(UnityGameObjectNames)))
    {
Debug.Log(unityName + " myObjectName");
    }




as always a few lines of sample code of Unity3d Enum and Foreach:
Sample1:

        //foreach (Madalyalar madalya in (Madalyalar[])Madalyalar.GetValues(typeof(Madalyalar)))
        foreach (Madalyalar madalya in Madalyalar.GetValues(typeof(Madalyalar)))
        {
            Debug.Log(madalya);
            //if (PlayerPrefs.GetInt("m_" + madalya, 0) == 1) {
            //}
        }


Sample 2:
int madalyaDurumu=0;
foreach (MadalyaTipleri madalya in (MadalyaTipleri[])MadalyaTipleri.GetValues(typeof(MadalyaTipleri)))
{
//kazaılmısmadalyalar listesinde var mı ?
if(kazanilmisMadalyalar.Contains(madalya)) {
continue;
}
//eger listede yok ise, playerprefs'e bak, daha önceden kaydedilmis ise listeye ekle.
            madalyaDurumu = PlayerPrefs.GetInt(madalya.ToString());
if(madalyaDurumu == 1) {
kazanilmisMadalyalar.Add(madalya);
}
}

No comments:

Post a Comment