zoukankan      html  css  js  c++  java
  • [Unity-22] Coroutine协程浅析

    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


  • 相关阅读:
    MS对SharePoint的支持力度...?
    一个很Cool的特性
    朋友landws做的一个ORM Component
    今天才知道原来IE扩展了一个showModalDialog()
    解决了那个SharePoint的小问题
    工作、SOA、MBF…
    DiskBased Caching in Whidbey, Longhorn...
    昨晚上写的关于IBuySpy里面用户权限验证方面的东西
    昨晚上写的关于IBuySpy里面用户权限验证方面的东西
    加入定制的WebService到SharePoint站点中
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7183434.html
Copyright © 2011-2022 走看看