Unity的C#編程教程_36_while循環語句
-
do while 循環
- 首先執行用於循環的程式塊
- 再進行條件判斷
- 判斷為真則再次運行程式塊
- 直到判定為假
- 跳出循環
-
比如數數程式:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoWhile : MonoBehaviour
{
public int num = 0;
// Start is called before the first frame update
void Start()
{
do
{
num++; // 每次數一個
} while (num < 10); // 數到 10 截止,跳出循環
}
// Update is called once per frame
void Update()
{
}
}
- 這裡需要注意的是,在程式塊裡面需要改變一個指示標誌,然後在後面對這個指示標誌進行條件判斷
- 這裡的例子中 num 就是指示標誌,如果沒有 num++,則會無限循環下去
-
While 循環
- 先判斷條件是否成立
- 成立再執行循環程式塊
- 然後再判斷條件是否成立,不成立則跳出循環
-
在協程中,有時會會搭配無限循環的 While 語句,即直接設定條件永遠為 true
-
比如在遊戲中,我們要隔一段時間就刷行一個地區的野怪,那就可以用攜程+無限循環的方式
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnEnemy : MonoBehaviour
{
public int enemyNum;
// Start is called before the first frame update
void Start()
{
StartCoroutine(SpawnEnemyRoutine()); // 啟動協程
}
// Update is called once per frame
void Update()
{
}
IEnumerator SpawnEnemyRoutine() // 定義協程
{
while (true)
{
yield return new WaitForSeconds(1.0f); // 等待 1 秒
enemyNum++; // 刷新一個敵人
}
}
}
- 這裡注意,協程的作用是等待一段時間
- 所以如果不用協程,直接把無限循環放在主遊戲程式中,那程式會崩潰
- 這個時候你一旦啟動運行測試遊戲,那所有未保存的東西可都要付之東流了
- While 語句的普通使用方式:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoWhile : MonoBehaviour
{
public int num = 0;
// Start is called before the first frame update
void Start()
{
while (num < 10) // num=10 的時候跳出循環
{
num++; // 每次加1
}
}
// Update is called once per frame
void Update()
{
}
}