码迷,mamicode.com
首页 > 编程语言 > 详细

[Unity-22] Coroutine协程浅析

时间:2015-03-19 11:31:34      阅读:374      评论:0      收藏:0      [点我收藏+]

标签:unity   线程   协程   coroutine   yield   

1.概念解释
       协程并不是一个独立的线程,在Unity中,所有的语句都是在一个线程中执行的,也就是说,Unity是单线程的(具体的可以参见http://blog.csdn.net/alexander_xfl/article/details/41577625,这里面有对单线程的粗略讲解)。
    那么协程到底是什么呢?
    官方的定义是这样的:

    A coroutine is a function that is executed partially and, presuming suitable conditions are met, will be resumed at some point in the future until its work is done

.协程是一个分部执行,遇到条件(yield return 语句)会挂起,直到条件满足才会被唤醒继续执行后面的代码。
实际上协程在后台与Update的执行原理是一样的,每一帧都会去判断是否满足执行条件,并据此判断是否执行。
2.作用与用法
a>延时一段时间
<span style="font-family:SimSun;">IEnumerator Fun() {
    yield returnnewWaitForSeconds(5.0F);
    //do something
}</span>

后面的代码会在延时5秒之后执行


b>等待其他事件完成

<span style="font-family:SimSun;">IEnumerator Do() {
    print("1");
    yield returnnewWaitForSeconds(2);
    print("2");
}
IEnumerator Fun() {
    print("3")
    yield returnStartCoroutine(Do());
    print("4");
}</span>

执行Fun后,输出顺序为:3 1 2 4
c>开启一个伪线程做其他工作
<span style="font-family:SimSun;">IEnumerator Do() {
        print("1");
        yield return new WaitForSeconds(2);
        print("2");
    }
    void Fun() {
        print("3");
        StartCoroutine(Do());
        print("4");
    }</span>

执行Fun后,输出顺序为:3 1 4 2
d>等一帧
<span style="font-family:SimSun;">Ienumerator Do()
{
    while(true)
{
    print("happy");
    yield return null;//等待这一帧结束
    //yield return new WaitForFixedUpdate(); //等待所有脚本的fixedupdate执行完毕
    //yield return new WaitForEndOfFrame();
}
}</span>


e>等待下载完成
<span style="font-family:SimSun;">yield return new WWWContinue()</span>
f>yield break
不再执行后续语句
这里只是对Unity协程进行了简单的介绍和基本用法分析,其实网上已经有了一些对Unity协程更透彻的分析,例如http://dsqiu.iteye.com/blog/2029701?utm_source=tuicool


[Unity-22] Coroutine协程浅析

标签:unity   线程   协程   coroutine   yield   

原文地址:http://blog.csdn.net/alexander_xfl/article/details/44454761

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!