Unity的C#編程教程_34_for循環語句挑戰2數蘋果

  • 使用協同程序(協程 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 秒
        }
    }
}

Tags: