赞
踩
yield return
和 yield break
是 C# 中迭代器方法的关键字,它们在 Unity 协程中被用来控制协程的执行流程。而 WaitForSeconds
、WaitUntil
和 WaitWhile
是 Unity 内置的 Yield Instruction 类型,用于实现异步等待特定条件满足时继续执行协程。
yield return
语句在协程(IEnumerator)中使用,允许函数在执行过程中暂停并返回一个值给调用者。StartCoroutine
调用包含 yield return
的函数时,该函数不会像普通函数那样立即执行到底,而是每遇到一次 yield return
就会暂停并返回当前的“结果”(可以是任意类型,包括各种 Yield Instruction),然后在下一帧或指定条件满足时继续执行后续代码。yield return new WaitForSeconds(2f);
表示协程将暂停执行2秒后继续。yield break;
在协程中表示终止整个迭代过程,相当于跳出整个协程。yield break;
执行时,协程会立刻停止,不会执行任何剩余的 yield return
语句。WaitForSeconds(float seconds)
是一个 Yield Instruction 类型,当它作为 yield return
的返回值时,会让协程暂停指定秒数之后再继续执行。IEnumerator MyCoroutine()
{
Debug.Log("Coroutine start");
yield return new WaitForSeconds(3);
Debug.Log("Coroutine resumes after 3 seconds");
}
void Start()
{
StartCoroutine(MyCoroutine());
}
WaitUntil(Func<bool> predicate)
接收一个布尔函数作为参数,在该函数返回 true
之前,协程会一直暂停执行。bool isPlayerReady = false;
IEnumerator WaitForPlayerReady()
{
while (!isPlayerReady)
{
yield return new WaitUntil(() => isPlayerReady);
}
Debug.Log("Player is now ready!");
}
public void SetPlayerReady() { isPlayerReady = true; }
WaitWhile(Func<bool> predicate)
类似于 WaitUntil
,但是它会一直等待直到传入的布尔函数返回 false
。float countdown = 5f;
IEnumerator Countdown()
{
while (countdown > 0)
{
Debug.Log(countdown.ToString());
countdown -= Time.deltaTime;
yield return new WaitWhile(() => countdown > 0);
}
Debug.Log("Countdown finished!");
}
yield return new WaitForEndOfFrame();
yield return new WaitForFixedUpdate();
using UnityEngine.Networking; IEnumerator LoadWebData() { UnityWebRequest www = UnityWebRequest.Get("http://example.com/data.json"); yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.Success) { Debug.Log(www.downloadHandler.text); } else { Debug.LogError(www.error); } }
public class CustomYieldInstruction : IEnumerator
{
public bool MoveNext() { ... } // 实现你的条件判断逻辑
public void Reset() { throw new NotSupportedException(); } // Unity通常不使用Reset方法
object IEnumerator.Current => null; // 因为Yield Instruction只需要MoveNext返回值,所以Current返回null
}
IEnumerator MyCoroutine()
{
yield return new CustomYieldInstruction();
// 当CustomYieldInstruction的MoveNext返回true时,这里将继续执行
}
在Unity中,除了标准的Yield Instruction之外,还有一些不那么常见但同样有用的等待机制:
yield return new WaitForSecondsRealtime(float seconds);
WaitForSeconds
,但是其计时不受Time.timeScale的影响,即使游戏时间被暂停(如Time.timeScale设置为0),该指令依然会按照真实时间进行等待。IEnumerator AnotherCoroutine()
{
// ...
}
IEnumerator WaitForAnotherCoroutine()
{
var waitForCompletion = StartCoroutine(AnotherCoroutine());
yield return waitForCompletion;
Debug.Log("AnotherCoroutine has finished.");
}
WaitUntil
或WaitWhile
来监听组件事件的发生。public class MyComponent : MonoBehaviour
{
public UnityEvent OnEventTriggered;
void Start()
{
StartCoroutine(WaitForEvent());
}
IEnumerator WaitForEvent()
{
yield return new WaitUntil(() => OnEventTriggered != null && OnEventTriggered.IsInvoking);
Debug.Log("Event was triggered!");
}
}
以上这些方法和机制进一步丰富了Unity中协程的功能和应用场景,让开发者能够根据实际需求灵活地编写异步任务流程。
python推荐学习汇总连接:
50个开发必备的Python经典脚本(1-10)
50个开发必备的Python经典脚本(41-50)
————————————————
最后我们放松一下眼睛
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。