日期:2014-05-17  浏览次数:20873 次

Unity3D使用C#实现Coroutines & Yield

Coroutines & Yield是Unity 3D编程中重要的概念,它可以实现将一段程序 延迟执行或者将其各个部分分布在一个时间段内连续执行,但是在Javascript与C#中实现Coroutines & Yield,在语法上却有一些区别:
yield不可单独使用
需要与return配合使用,例如:
1 yield return 0; //等0帧??
2 yield return 1; //等1帧??
3 yield return WaitForSeconds(3.0); //等待3秒
所有使用yield的函数必须将返回值类型设置 为IEnumerator类型,例如:
1 IEnumerator DoSomeThingInDelay() {...}
最后,也是在”Using C#”这个章节中没有讲到的关键一点是,所有IEnumerator类型函数必须使用”StartCoroutine”这个函数触发,不能单独使用,例如:
1 StartCoroutine(DoSomeThingInDelay());
最后附上学习 Coroutines & Yield时所做的小例子脚本 的作用是不断随机改变材质 的颜色,演示 demo使用”V字仇杀队”中的面具。
01 using UnityEngine;??
02 using System.Collections;??
03? ?
04 public class RandomColor : MonoBehaviour {??
05? ?
06??public float delayInSecond = 1;??
07??public Material targetMaterial;??
08? ?
09??// Use this for initialization??
10??void Start () {??
11??StartCoroutine(AutoChangeColor());??
12??}??
13? ?
14??// Update is called once per frame??
15??void Update () {??
16??}??
17? ?
18??IEnumerator AutoChangeColor()??
19??{??
20??yield return 0; //确保Time.deltaTime为0??
21? ?
22??Color colorNew = GenerateRandomColor();??
23??Color colorNow = targetMaterial.GetColor("_Color");??
24??float timeEclapsed = 0;??
25??for (timeEclapsed = 0; timeEclapsed < delayInSecond; timeEclapsed += Time.deltaTime)??
26??{??
27??float progress = timeEclapsed / delayInSecond;??
28??Color colorTween = new Color(??
29??(colorNew.r - colorNow.r) * progress + colorNow.r,??
30??(colorNew.g - colorNow.g) * progress + colorNow.g,??
31??(colorNew.b - colorNow.b) * progress + colorNow.b??
32??);??
33??targetMaterial.SetColor("_Color", colorTween);??
34??yield return 1;??
35??}??
36? ?
37??StartCoroutine(AutoChangeColor());??
38??}??
39? ?
40??Color GenerateRandomColor(){??
41??Color color = new Color();??
42??color.r = Random.value;??
43??color.g = Random.value;??
44??color.b = Random.value;??
45? ?
46??return color;??
47??}??
48 }