using
UnityEngine;
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.deltaTime;
if
(thirdTimer <= 0)
Debug.Log(
"Third timer has finished!"
);
}
}
不算太糟,但是个人感觉不太喜欢这些个计时器变量在代码中,而且我不得不去重启计时器。
for
(
float
timer = 3; timer >= 0; timer -= Time.deltaTime)
{
//Just do nothing...
}
Debug.Log(
"This happens after 5 seconds!"
);
这个要好多了,因为现在每个计时器的变量就是每个循环中的一部分。
下面是coroutine代码实例:
using
UnityEngine;
using
System.Collections;
public
class
CoroutineCountdown : MonoBehaviour
{
void
Start()
{
StartCoroutine(Countdown());
}
IEnumerator Countdown()
{
for
(
float
timer = 3; timer >= 0; timer -= Time.deltaTime)
yield
return
0;
Debug.Log(
"This message appears after 3 seconds!"
);
}
}
StartCoroutine(Countdown());
这句话就是开始我们countdown方法。
When you “yield” a function, you’re effectively saying, “Stop this function now, then resume from here the next frame!”
当你使用yield方法时候,意味着,从这个现在起停止这个方法,然后返回去执行下一帧。
秒计数:
IEnumerator CountSeconds()
{
int
seconds = 0;
while
(
true
)
{
for
(
float
timer = 0; timer < 1; timer += Time.deltaTime)
yield
return
0;
seconds++;
Debug.Log(seconds +
" seconds have passed since the Coroutine started."
);
}
}
Starting & Stopping Coroutines
startCoroutine ( FirstTimer () );
startCoroutine ( SecondTimer () );
//If you start a Coroutine by name...
StartCoroutine(
"FirstTimer"
);
StartCoroutine(
"SecondTimer"
);
//You can stop it anytime by name!
StopCoroutine(
"FirstTimer"
);
|
原文引用:http://unitypatterns.com/introduction-to-coroutines/