Unity3D等待函数介绍

Unity3D等待函数介绍。Coroutines & Yield是Unity3D编程中重要的概念,它可以实现将一段程序延迟执行或者将其各个部分分布在一个时间段内连续执行,但是在Javascript与C#中实现Coroutines & Yield,在语法上却有一些区别:

yield不可单独使用需要与return配合使用,例如:

yield return 0; //等0帧

yield return 1; //等1帧

yield return WaitForSeconds(3.0); //等待3秒

所有使用yield的函数必须将返回值类型设置为IEnumerator类型,例如:

IEnumerator DoSomeThingInDelay() {...}

最后,也是在”Using C#”这个章节中没有讲到的关键一点是,所有IEnumerator类型函数必须使用”StartCoroutine”这个函数触发,不能单独使用,例如:

StartCoroutine(DoSomeThingInDelay());

最后附上学习Coroutines & Yield时所做的小例子,脚本的作用是不断随机改变材质的颜色。

脚本如下:

using UnityEngine;
using System.Collections;
public class RandomColor : MonoBehaviour {

public float delayInSecond = 1;
public Material targetMaterial;

// Use this for initialization
void Start () {
StartCoroutine(AutoChangeColor());
}
// Update is called once per frame
void Update () {
}

IEnumerator AutoChangeColor()
{
yield return 0; //确保Time.deltaTime为0
Color colorNew = GenerateRandomColor();
Color colorNow = targetMaterial.GetColor("_Color");
float timeEclapsed = 0;
for (timeEclapsed = 0; timeEclapsed < delayInSecond; timeEclapsed += Time.deltaTime)
{
float progress = timeEclapsed / delayInSecond;
Color colorTween = new Color(
(colorNew.r - colorNow.r) * progress + colorNow.r,
(colorNew.g - colorNow.g) * progress + colorNow.g,
(colorNew.b - colorNow.b) * progress + colorNow.b
);
targetMaterial.SetColor("_Color", colorTween);
yield return 1;
}

StartCoroutine(AutoChangeColor());
}

Color GenerateRandomColor(){
Color color = new Color();
color.r = Random.value;
color.g = Random.value;
color.b = Random.value;

return color;
}
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值