本篇为大三游戏开发课程作业/笔记之一,内容未进行修改,暂记录于此。
1.研究目的
Unity 中各个函数有固定的执行顺序,为了防止某些操作阻塞程序运行,Unity 提供了 yield 函数。
2.研究内容
(1)查阅Unity官方文档及有关资料,总结Yield的典型用法及作用
(2)编写Coroutine函数,控制场景中Cube的材颜色在红色、绿色、蓝色之间循环切换,并且每种颜色的持续时间在1到3秒之间随机变化。
3.研究过程
3.1.Yield典型用法及作用
一个协程的执行可以在任何地方用yield语句来暂停,yield return的值决定了什么时候协程恢复执行。协程在协调在几帧中执行的操作时有极大的用处。协程几乎没有任何性能开销。
yield return的常见返回值及其作用:
- yield return new WaitForSeconds(3.0f);
等待3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后(这里的时间会受到Time.timeScale的影响); - yield return null;
这一帧到此暂停,下一帧再从暂停处继续,常用于循环中。 - yield return 1;
这一帧到此暂停,下一帧再从暂停处继续。这里return什么都是等一帧,后面的返回值没有特殊意义。所以返回0或1或100都是一样的。 - yield break;
直接结束该协程的后续操作。 - yield return StartCoroution(某个协程);
等待某个协程执行完毕后再执行后续代码。 - yield return WWW();
等待WWW操作完成后再执行后续代码。
3.2.程序实例
实现代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testYield : MonoBehaviour {
public GameObject cub;
// Use this for initialization
void Start () {
StartCoroutine(CoroutineTest());
}
// Update is called once per frame
void Update () {
}
IEnumerator CoroutineTest()
{
while(true)
{
cub.GetComponent<Renderer>().material.color = Color.red;//材质转为红色
yield return new WaitForSeconds(randomtime());//等待几秒
Debug.Log(string.Format("ColorRed:Timer is up !!! time=${0} ", Time.time));//输出材质为红色的时间
cub.GetComponent<Renderer>().material.color = Color.green;//材质转为绿色
yield return new WaitForSeconds(randomtime());//等待几秒
Debug.Log(string.Format("ColorGreen:Timer is up !!! time=${0} ", Time.time));//输出材质为绿色的时间
cub.GetComponent<Renderer>().material.color = Color.blue;//材质转为蓝色
yield return new WaitForSeconds(randomtime());//等待几秒
Debug.Log(string.Format("ColorBlue:Timer is up !!! time=${0} ", Time.time));//输出材质为蓝色的时间
}
}
float randomtime() //在1-3s内的随机时间
{
float Ti = Random.Range(1, 3);
return Ti;
}
}
3.3.运行结果
最开始的模型如下:

运行时:
刚开始运行立方体为红色,切换为绿色后,Console显示了红色停留的时间;而在绿色切换为蓝色后,Console显示了绿色停留的时间;在立方体颜色由蓝色切换为红色时,显示了蓝色停留的时间。




浙公网安备 33010602011771号