Unity3D使用C#实现Coroutines & Yield

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

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

[csharp]
yield return 0; //等0帧
yield return 1; //等1帧
yield return WaitForSeconds(3.0); //等待3秒
[/csharp]

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

[csharp]
IEnumerator DoSomeThingInDelay() {…}
[/csharp]

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

[csharp]
StartCoroutine(DoSomeThingInDelay());
[/csharp]

[csharp]using UnityEngine;
using System.Collections;

public class RandomColor : MonoBehaviour
{

public float delayInSecond = 1;
public Material targetMaterial;

// Use this for initialization
void Start ()
{
StartCoroutine (AutoChangeColor ());
}

IEnumerator AutoChangeColor ()
{
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;
}
}[/csharp]

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据