using UnityEngine;
using System.Collections;
public class WhileLoop : MonoBehaviour
{
int cupsInTheSink = 4;
void Start ()
{
while (cupsInTheSink > 0)////(1)
{
Debug.Log("I've washed a cup");
cupsInTheSink--;////(2)
}
}
}
(1)while迴圈當括號中的條件成立時,會一直重複執行{}中的內容,直到條件不符合為止。(2)當每次執行這個while迴圈時,會將cupsInTheSink變數減1,所以當cupsInTheSink數值為4、3、2、1都會執行迴圈,合計執行四次,執行第五次數值為0時迴圈結束。
執行結果如下。
接著是do-while迴圈,以下是範例。
using UnityEngine;
using System.Collections;
public class DoWhileLoop : MonoBehaviour
{
void Start ()
{
bool shouldContinue = false;
do////(1)
{
Debug.Log("Hello World");
} while (shouldContinue == true);////(2)
}
}
do-while迴圈語法類似while迴圈,但do-while迴圈的條件判斷是在執行完迴圈之後,while迴圈則是在迴圈開始前。(1)從do開始執行迴圈,由於條件判斷會在迴圈結束後才執行,所以do-while迴圈必定執行一次。
(2)迴圈的條件判斷,要注意的是while最後是有;的。
執行結果如下。
再來是for迴圈,以下是範例。
using UnityEngine;
using System.Collections;
public class ForLoop : MonoBehaviour
{
int numEnmies = 3;
void Start ()
{
for (int i = 0; i < numEnmies; i++)////
{
Debug.Log("Creating enemy number: " + i);
}
}
}
相對於前面的while迴圈,for迴圈的規則就嚴謹許多,除了條件判斷外,還多了初始值與更新值。迴圈語法為for(起始值; 條件式; 更新值);,迴圈執行的流程為:
(1)給定初始值int i = 0。
(2)判斷i < numEnmies是否成立,成立執行迴圈,不成立結束迴圈。
(3)執行迴圈內容Debug.Log("Creating enemy number: " + i);。
(4)執行完畢後回到開頭更新數值,也就是i++。
(5)回到(2)的動作。
執行結果如下。
最後是foreach迴圈,以下是範例。
using UnityEngine;
using System.Collections;
public class ForeachLoop : MonoBehaviour {
void Start ()
{
string[] strings = new string[3];
strings[0] = "First string";
strings[1] = "Second string";
strings[2] = "Third string";
foreach (string item in strings)////(1)
{
Debug.Log(item);////(2)
}
}
}
foreach迴圈非常適合處理陣列中的元素。(1)迴圈語法為foreach(元素 in 陣列),而迴圈會在陣列的所有元素都依序處理完為止。
(2)例如這裡的item在執行迴圈第一次數值為strings[0],第二次數值為strings[1],以此類推。
執行結果如下。
以上就是迴圈的說明。
這次就到這裡。





沒有留言:
張貼留言