Unity3D实现CoroutinesYield延迟代码
slug: Unity3D实现Coroutines_Yield延迟代码
Unity3D C#实现Coroutines & Yield延迟代码
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时所做的小例子,脚本的作用是不断随机改变材质的颜 色,演示demo使用”V字仇杀队”中的面具。
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; 
    } 
}