0

I have a simple enum value type for 3 camera modes. I know how to print out each value (e.g. Debug.Log(OrbitStyle.Smooth) or Debug.Log(OrbitStyle.Smooth.ToString())) but in order to print them all out, I thought I had to write a function for it.

My first question is: Is this the only way to do so, or is there a function for looping through enums?

My second question is: Why does my Unity3D program crashes when I add = to include all values, while incrementing/decrementing? The program below prints out Smooth, Step and then Fade, Step but I use <= or >= to include the least and highest values as well, but it always crashes. What am I doing wrong?

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


public class CameraOribit : MonoBehaviour
{
    enum OrbitStyle
    {
        Smooth,
        Step,
        Fade
    }


    void Start()
    {
        for ( OrbitStyle e1 = OrbitStyle.Smooth; e1 < OrbitStyle.Fade; e1 = IncrementEnum(e1) )
        {
            Debug.Log(e1);
        }

        for ( OrbitStyle e2 = OrbitStyle.Fade; e2 > OrbitStyle.Smooth; e2 = DecrementEnum(e2) )
        {
            Debug.Log(e2);
        }
    }


    static OrbitStyle IncrementEnum(OrbitStyle e)
    {
        if (e == OrbitStyle.Fade)
            return e;
        else
            return e + 1;
    }

    static OrbitStyle DecrementEnum(OrbitStyle e)
    {
        if (e == OrbitStyle.Smooth)
            return e;
        else
            return e - 1;
    }
}
Jerry Switalski
  • 2,690
  • 1
  • 18
  • 36

1 Answers1

0

For your first question, you can see the answer here: Can you loop through all enum values?

For your second question, the nature of a for loop is:

for (OrbitStyle e1 = OrbitStyle.Smooth; e1 <= OrbitStyle.Fade; e1 = IncrementEnum(e1)) {
  Debug.Log(e1);
}

Equal:

OrbitStyle e1 = OrbitStyle.Smooth;
while(e1 <= OrbitStyle.Fade){
    Debug.Log(e1);
    e1 = IncrementEnum(e1);
}

Now, as you can see, at the end of the loop (when e1 == OrbitStyle.Fade), the condition return true so the code run, and at the end, when IncrementEnum(e1) is called once more, e1 is already at the maximum number of the enum, and trying to increase it again result in a crash.

Community
  • 1
  • 1
AVAVT
  • 7,058
  • 2
  • 21
  • 44