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: