unity3d协同程序学习笔记

       一个协同程序在执行过程中,可以在任意位置使用yield语句。yield的返回值控制何时恢复协同程序向下执行。协同程序在对象自有帧执行过程中堪称优秀。协同程序在性能上没有更多的开销。StartCoroutine函数是立刻返回的,但是yield可以延迟结果。直到协同程序执行完毕。

function StartCoroutine(routine : IEnumerator) : Coroutine

One example:

usingUnityEngine;

usingSystem.Collections;

 

public classexample : MonoBehaviour {

          void Start() {

          print("Starting " + Time.time);//firstprint

                    StartCoroutine(WaitAndPrint(2.0F));

                    print("BeforeWaitAndPrint Finishes " + Time.time);//secondprint

          }

          IEnumerator WaitAndPrint(floatwaitTime) {

                    yield return new WaitForSeconds(waitTime);

                    print("WaitAndPrint" + Time.time);//lastprint

          }

}

IEnumerable是一个声明式的接口,声明实现该接口的class可枚举(enumerable的,但并没有说明如何实现枚举器(iterator);IEnumerator是一个实现式的接口,IEnumeratorobject就是一个iterator(通过MoveNext()Reset()Current)。

 

Another example:

function StartCoroutine(methodName : string, value : object = null) : Coroutine

// In this example we show how toinvoke a coroutine using a string name and stop it

// 这个例子演示如何调用一个使用字符串名称的协同程序并停掉它

functionStart () {

          StartCoroutine("DoSomething",2.0);

          yield WaitForSeconds (1);

          StopCoroutine("DoSomething");

}

 

functionDoSomething (someParameter : float) {

          while (true) {

                    print("DoSomethingLoop");

                    // Yield execution of this coroutineand return to the main loop until next frame

                        //停止协同程序的执行并返回到主循环直到下一帧.

                    yield;

          }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值