在Unity中制作计时器 [英] Making a timer in Unity
问题描述
我在Unity中遇到问题.我的项目需要倒数计时.但是,此倒计时将计数2次.例如,将完成一项工作3秒,完成另一项工作2秒,然后这些工作将继续.
I have a problem in Unity. I need a countdown in my project. But this countdown will count 2 times. For example, 3 seconds a job will be done, 2 seconds another job will be done and these works will continue.
推荐答案
协程(以及更多协程)
协程完全可以完成您想做的事情.
Couroutines (and more Coroutines)
Coroutines do exactly the thing you want to do.
private IEnumerator Countdown2() {
while(true) {
yield return new WaitForSeconds(2); //wait 2 seconds
//do thing
}
}
private IEnumerator Countdown3() {
while(true) {
yield return new WaitForSeconds(3); //wait 3 seconds
//do other thing
}
}
然后,您可以通过调用Start()
方法(或任何地方)来启动它们:
You then start them off by calling in your Start()
method (or where ever):
void Start() {
StartCoroutine(Countdown2());
StartCoroutine(Countdown3());
}
请注意,除非发生以下三种情况之一,否则这两种倒计时方法都会永远起作用:
Note that both countdown methods will do their thing forever unless one of three things happens:
-
调用
-
StopCoroutine(...)
,传入StartCoroutine
返回的引用
- 倒数功能本身返回(除非它打破无限
while(true)
循环,否则不会发生) - coundown函数本身调用
yield break
StopCoroutine(...)
is called, passing in the reference returned byStartCoroutine
- The countdown function itself returns (which will not happen unless it breaks out of the infinite
while(true)
loop) - The coundown function itself calls
yield break
还要注意,如果两个协程都应在同一时间(例如6秒)恢复,协程2将首先执行(首先启动),除非有其他效果干预(例如,其中一个循环具有另一个yield
指令,其中一个循环终止,等等).
Also note that in the event both coroutines should resume at the same time (e.g. at 6 seconds) coroutine 2 will execute first (as it was started first), unless some other effect intervenes (e.g. one of the loops has another yield
instruction, one of the loops is terminated, etc).
这篇关于在Unity中制作计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!