Unity的协程系统是基于C#的一个简单而强大的接口,IEnumerator,它允许你为自己的集合类型编写枚举器。这一点你不必关注太多。
倒计时器:这是一个简单的脚本组件,只做了倒计时,并且在到达0的时候log一个信息。
using Unity Engine;
using System.Collections;
public class Countdown : MonoBehaviour
{
public float timer = 3;
void Update()
{
timer -= Time.deltaTime;
if(timer <= 0)
Debug.Log("Timer has finished!");
}
}
代码简短实用,但问题是,如果我们需要复杂的脚本组件(像一个角色或者敌人的类),拥有多个计时器呢?
刚开始的时候,我们的代码也许会是这样的:
using UnityEngine;
using System.Collections;
public class MultiTimer : MonoBehaviour
{
public float firstTimer = 3;
public float secondTimer = 2;
public float thirdTimer = 1;
void Update()
{
firstTimer -= Time.deltaTime;
if(firstTimer <= 0)
Debug.Log("First timer has finished!");
secondTimer -= Time.deltaTime;
if(secondTimer <= 0)
Debug.Log("Second timer has finished!");
thirdTimer -= Time.de