Unity 3D脚本编程与游戏开发【5.6】

13.2.3 协程的延时执⾏原理

        上⼀⼩节的例⼦展⽰了迭代器函数的使⽤⽅法,但是它是在1帧内直接运⾏完毕的,没有体现出“延时运⾏”的功能。下⾯对它做⼀些改动,引⼊定时功能。

using System.Collections.Generic;
using UnityEngine;
public class MyIter2 : MonoBehaviour
{
IEnumerator<int> HelloWorld()
{
transform.position = new Vector3(1, 0, 0);
yield return 1;
transform.position = new Vector3(2, 0, 0);
yield return 2;
transform.position = new Vector3(3, 0, 0);
yield return 1;
}
IEnumerator<int> e;
float helloTime = 0;
void Start()
{
e = HelloWorld();
}
void Update()
{
if (e != null)
{
if (Time.time > helloTime)
{
if (!e.MoveNext())
{
// 协程结束了
e = null;
return;
}
Debug.Log("yield返回值:"+e.Current);
// 把返回值当作延迟的时间
helloTime = Time.time + e.Current;
}
}
}
}

        将这个脚本挂载到⽴⽅体上,运⾏游戏,可以展⽰出⽴⽅体间隔1~2秒改变⼀次位置的效果。注意这个脚本与第⼀个迭代器脚本最⼤的区别在于,e.MoveNext⽅法是在Update函数中执⾏的。Update函数每帧调⽤,不需要再使⽤循环。
       

  • 21
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BinaryStarXin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值