Unity的C#編程教程_34_for循環語句挑戰2數蘋果
- 2020 年 8 月 21 日
- AI
- C/C++/C#
- 使用協同程式(協程 Coroutine),來分解循環程式
- 設計一個數蘋果的程式,每隔1秒數一次
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CountApples : MonoBehaviour
{
public int apples;
// Start is called before the first frame update
void Start()
{
StartCoroutine(CountApplesRoutine()); // 啟用協程
}
// Update is called once per frame
void Update()
{
}
IEnumerator CountApplesRoutine() // 設計協程
{
for(int i = 0; i < 20; i++)
{
apples++; // 數一個蘋果
yield return new WaitForSeconds(1.0f); // 等待 1 秒
}
}
}