unity yield return 的用法
时间: 2023-09-28 12:06:08 浏览: 73
Unity中的yield return是用来控制协程(Coroutine)执行流程的关键字。协程是一种特殊的函数,可以在执行过程中暂停并在稍后继续执行,而不会阻塞主线程。
yield return语句可以在协程函数中使用,它的作用是将控制权交还给调用协程的代码,并且可以返回一个值。具体来说,yield return语句可以用于以下几种情况:
1. 等待一段时间:
```
IEnumerator MyCoroutine()
{
Debug.Log("Coroutine started");
yield return new WaitForSeconds(1.0f);
Debug.Log("Coroutine resumed after 1 second");
}
```
在这个例子中,协程会等待1秒钟,然后再继续执行后面的代码。
2. 等待帧更新:
```
IEnumerator MyCoroutine()
{
Debug.Log("Coroutine started");
yield return null;
Debug.Log("Coroutine resumed in the next frame");
}
```
这个例子中,yield return null语句会让协程暂停一帧,并在下一帧继续执行。
3. 等待其他协程完成:
```
IEnumerator CoroutineA()
{
Debug.Log("Coroutine A started");
yield return StartCoroutine(CoroutineB());
Debug.Log("Coroutine A resumed after Coroutine B finished");
}
IEnumerator CoroutineB()
{
Debug.Log("Coroutine B started");
yield return new WaitForSeconds(2.0f);
Debug.Log("Coroutine B finished
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)