01 3秒后执行随机显示0到10的一个数。
02 模拟协程下载资源主线程不卡顿。
//Unity-协程
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//01 3秒后执行随机显示0到10的一个数。
//02 模拟协程下载资源主线程不卡顿。
public class Demo : MonoBehaviour
{
void Start()
{
for (int i = 0; i < 100; i++)
{
StartCoroutine(wait(3));
}
StartCoroutine(loading());
loading2();
}
//延时操作
IEnumerator wait(int intSceond)
{
//延时操作,yield return new WaitForSeconds(intSceond);后面的代码延时制定的时间操作。
yield return new WaitForSeconds(intSceond);
Debug.Log("3秒后执行");
Debug.Log("Random.Range(0, 11) = " + Random.Range(0, 11));
}
//异步处理,类似子线程操作,UI主线程还是可以刷新
IEnumerator loading()
{
//如果放这里,会暂缓一帧后,后面快速循环执行。
//yield return null;
int num = 0;
for (int i = 0; i < 100; i++)
{
//假如加载100个资源,画面不卡。
num++;
Debug.Log("num = " + num);
//yield return null表示暂缓一帧,在下一帧接着往下处理。
//放在这里,会循环暂缓一帧。这里会暂缓100次,这里的for循环执行会比较慢。
//StartCoroutine(loading());和loading2();执行后,这里会暂缓一帧,loading2()里的for循环会全部执行外,loading里才会for循环加继续1,num的值变为2。
yield return null;
}
}
public void loading2()
{
int num2 = 0;
for (int i = 0; i < 100; i++)
{
//假如加载100个资源,画面会卡。
num2++;
Debug.Log("num2 = " + num2);
}
}
}
运行结果