协程就是:你可以写一段顺序的代码,然后标明哪里需要暂停,然后在下一帧或者一段时间后,系统会继续执行这段代码
协程是一个分部执行,遇到条件(yield return 语句)会挂起,直到条件满足才会被唤醒继续执行后面的代
简单来说就是控制代码在特地时间运行
IEnumerator LongComputation()
{
while(someCondition)
{
/* 做一系列的工作 */
// 在这里暂停然后在下一帧继续执行
yield return null;
}
}
StartCoroutine(LongComputation())//启动协程运算
对协程是否执行进行条件判断
IEnumerator DoSomething(){
/* ... */}
IEnumerator DoSomethingUnlessInterrupted(){
IEnumerator e = DoSomething();
bool interrupted = false;
while(!interrupted)
{
e.MoveNext();
yield return e.Current;
interrupted = HasBeenInterrupted();
}}
实现延时的效果
IEnumerator WaitTurnDirection(float time)
{
yield return new WaitForSeconds(time);
}
IEnumerator TellMeASecret(){
PlayAnimation("LeanInConspiratorially");
while(playingAnimation)
yield return null;
Say("I stole the cookie from the cookie jar!");
while(speaking)
yield return null;
PlayAnimation("LeanOutRelieved");
while(playingAnimation)
yield return null;
}
然后我们可以使用下文这样的客户代码,来调用上文的程序,就可以实现延时的效果。
IEnumerator e = TellMeASecret();
while(e.MoveNext()) {
// do whatever you like
}
注意:如果在一个对象的前期调用协程,协程会立即运行到第一个 yield return 语句处,如果是 yield return null ,就会在同一帧再次被唤醒。
协程停止方法:通过gameObject.active = false 就可以停止协程的执行
IEnumerator & Coroutine
以上是我目前对协程的用法认识和理解,以后会继续完善补充