Unity Coroutines

来源:互联网 发布:pandas 数据分析 实例 编辑:程序博客网 时间:2024/06/06 16:44

When you call a function, it runs to completion before returning.This effectively means that any action taking place in a functionmust happen within a single frame update; a function call can't beused to contain a procedural animation or a sequence of events overtime. As an example, consider the task of gradually reducing anobject's alpha (opacity) value until it becomes completelyinvisible.

void Fade() {        for (float f = 1f; f >= 0; f -= 0.1f) {                Color c = renderer.material.color;                c.alpha = f;                renderer.material.color = c;        }}

As it stands, the Fade function will not have the effect you mightexpect. In order for the fading to be visible, the alpha must bereduced over a sequence of frames to show the intermediate valuesbeing rendered. However, the function will execute in its entiretywithin a single frame update. The intermediate values will never beseen and the object will disappear instantly.

It is possible to handle situations like this by adding code to theUpdate function that executes the fade on a frame-by-frame basis.However, it is often more convenient to use a coroutine for thiskind of task.

A coroutine is like a function that has the ability to pauseexecution and return control to Unity but then to continue where itleft off on the following frame. In C#, a coroutine is declaredlike this:-

IEnumerator Fade() {        for (float f = 1f; f >= 0; f -= 0.1f) {                Color c = renderer.material.color;                c.alpha = f;                renderer.material.color = c;                yield return;        }}

It is essentially a function declared with a return type ofIEnumerator and with the yield return statement included somewherein the body. The yield return line is the point at which executionwill pause and be resumed the following frame. To set a coroutinerunning, you need to use the StartCoroutine function:-

void Update() {        if (Input.GetKeyDown("f")) {                StartCoroutine("Fade");        }}

In UnityScript, things are slightly simpler. Any function thatincludes the yield statement is understood to be a coroutine andthe IEnumerator return type need not be explicitly declared:-

function Fade() {        for (var f = 1.0; f <= 0; f -= 0.1) {                var c = renderer.material.color;                c.alpha = f;                renderer.material.color = c;                yield;        }}

Also, a coroutine can be started in UnityScript by calling it as ifit were a normal function:-

function Update() {        if (Input.GetKeyDown("f")) {                Fade();        }}

You will notice that the loop counter in the Fade functionmaintains its correct value over the lifetime of the coroutine. Infact any variable or parameter will be correctly preserved betweenyields.

By default, a coroutine is resumed on the frame after it yields butit is also possible to introduce a time delayusing WaitForSeconds:-

IEnumerator Fade() {        for (float f = 1f; f <= 0; f -= 0.1f) {                Color c = renderer.material.color;                c.alpha = f;                renderer.material.color = c;                yield return new WaitForSeconds(.1f);        }}

...on in UnityScript

function Fade() {        for (var f = 1.0; f <= 0; f -= 0.1) {                var c = renderer.material.color;                c.alpha = f;                renderer.material.color = c;                yield WaitForSeconds(0.1);        }}

This can be used as a way to spread an effect over a period timebut it is also a useful optimization. Many tasks in a game need tobe carried out periodically and the most obvious way to do this isto include them in the Update function. However, this function willtypically be called many times per second. When a task doesn't needto be repeated quite so frequently, you can put it in a coroutineto get an update regularly but not every single frame. An exampleof this might be an alarm that warns the player if an enemy isnearby. The code might look something like this:-

function ProximityCheck() {        for (int i = 0; i < enemies.Length; i++) {                if (Vector3.Distance(transform.position, enemies[i].transform.position) < dangerDistance) {                                return true;                }        }        return false;}

If there are a lot of enemies then calling this function everyframe might introduce a significant overhead. However, you coulduse a coroutine to call it every tenth of a second:-

IEnumerator DoCheck() {        for(;;) {                ProximityCheck;                yield return new WaitForSeconds(.1f);        }}

This would greatly reduce the number of checks carried out withoutany noticeable effect on gameplay.


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机号码淘宝被注册跟换绑定怎么办 微信发送ppt显示文件太大怎么办 微信手机号丢了微信登不了钱怎么办 新买的号码注册过支付宝怎么办 新买的号码被注册过支付宝怎么办 支付宝同号码注册了新的帐号怎么办 新卖的号码有人注册过支付宝怎么办 我的号码被别人注册了支付宝怎么办 别人用我的号码注册了支付宝怎么办 打开支付宝进入到淘宝的界面怎么办 我的手机号注销了支付宝账号怎么办 微博绑定的支付宝账号注销了怎么办 闲鱼买家申请退款卖家不同意怎么办 微信与手机旧版本不一致怎么办 在应用宝里下载微信老是失败怎么办 使用u盘储存视频显示不兼容怎么办 支付宝下载显示与存在不兼容怎么办 cpu与64位系统不兼容怎么办 微信版本低登录不了怎么办苹果手机 手机版本低登录不了微信怎么办? 进入微信公众号显示登录失败怎么办 安卓系统手机亮度调到最低怎么办 阿里妈妈买家号虚假交易违规怎么办 淘宝商让我修改追评叫我怎么办 红冲金额大于了当月的销售额怎么办 淘宝买家号虚假交易评价删除怎么办 淘宝卖的宝贝电话写错了怎么办 邮政快递都揽件了一直不运输怎么办 应用宝里面的安装包安装不了怎么办 苹果平板电脑充电接口坏了怎么办 读书郎平板电脑开不了机怎么办 平板电脑死机开不了机了怎么办 欧灵平板电脑忘记图密解锁怎么办 淘宝没货发给人被投诉了怎么办 淘宝店铺既不能开又不能注销怎么办 妻子被骗五万疑似被洗脑我该怎么办 奖虫账号和密码不匹配怎么办 开淘宝店余额宝里的钱怎么办 京东找不到所有宝贝的链接了怎么办 淘宝店链接改了标题没流量怎么办 淘宝手淘搜索自然流量少怎么办