2017-02-25 103 views
0

對於3種相機模式,我有一個簡單的enum值類型。我知道如何打印出每個值(例如Debug.Log(OrbitStyle.Smooth)Debug.Log(OrbitStyle.Smooth.ToString())),但爲了全部打印出來,我想我必須爲它編寫一個函數。循環遍歷相機模式的枚舉

我的第一個問題是:這是唯一的方法這樣做,或者是否有一個函數循環通過enum s?

第二問題是:爲什麼我的Unity3D程序崩潰時,我添加=包括所有值,而遞增/遞減?下面的程序打印出Smooth, Step,然後Fade, Step,但我使用<=>=以包括最小值和最大值,但它總是崩潰。我究竟做錯了什麼?

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; 
    } 
} 

回答

1

關於第一個問題,你可以在這裏看到了答案:Can you loop through all enum values?

關於第二個問題,一個for循環的性質是:

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

平等:

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

現在,您可以看到,在循環結束時(當e1 == OrbitStyle.Fade ),則條件返回true,以便代碼運行,並且在最後再次調用IncrementEnum(e1)時,e1已處於枚舉的最大數目,並且嘗試再次增加它會導致崩潰。

+0

非常感謝您的幫助! – Joshua