理解:协程不是线程,也不是异步执行(知道就行)。
1.协程和MonoBehaviour的Update函数一样,也是在MainThread中执行的(一定得明白这句话意思)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
void
Start () {
StartCoroutine(HelloCoroutine());
}
void
Update () {
Debug.Log(
"Update..."
);
}
void
LateUpdate()
{
Debug.Log(
"LateUpdate..."
);
}
IEnumerator HelloCoroutine()
{
while
(
true
)
{
Debug.Log(
"Coroutine..."
);
yield
return
null
;
}
}
|
1
|
|
对比以上代码和两张截图。这样写协程,好像是高级一点的Update写法。至少应该可以看出,这种写法的协程可以完成update的功能。
2.与update不一样的地方。
1
2
3
4
5
6
7
8
9
10
11
12
|
IEnumerator Count()
{
int
seconds = 0;
while
(
true
)
{
for
(
float
timer = 0; timer < 2; timer += Time.deltaTime)
yield
return
0;
seconds++;
Debug.Log(seconds +
" seconds have passed since the Coroutine started."
);
}
}<br>
|
3.yield
yiled return null 等同于 yield return 0
我这边的理解是,停止正在执行的方法,并从下一帧开始执行(一般是0.02秒,与Update的每一帧是一样的,具体看Unity设置的timer)。
4.协程是可以传递参数的。
5.协程还可以嵌套协程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
IEnumerator HelloCoroutinue()
{
Debug.Log(
"Start----"
);
yield
return
StartCoroutine(Wait(0.2f));
// yield return new WaitForSeconds(0.2f);最终达到的效果是一样的。
Debug.Log(
"End----"
);
}
IEnumerator Wait(
float
s)
{
for
(
float
timer =0;timer< s;timer+=Time.deltaTime)
{
Debug.Log(
"当前 timer"
+ timer.ToString());
yield
return
0;
// yield return null;
}
Debug.Log(
"Wait....."
);
}
|
看截图中画线的时间差,再次验证了与Update好像。暂停的时间都是一样的。
可以看到暂停了当前的方法去执行yield return后的方法。
补充注意:
a.多个协程可以同时运行,它们会根据各自的启动顺序来更新;
b.如果你想让多个脚本访问一个协程,可以定义为静态的协程;