返回介绍

CustomYieldInstruction 自定义中断指令

发布于 2019-12-18 15:37:38 字数 3358 浏览 903 评论 0 收藏 0

Description 描述

Base class for custom yield instructions to suspend coroutines.

用于自定义中断指令来暂停协程的基类。

CustomYieldInstruction lets you implement custom yield instructions to suspend coroutine execution until an event happens. Under the hood, custom yield instruction is just another running coroutine. To implement it, inherit from CustomYieldInstruction class and override keepWaiting property. To keep coroutine suspended return true. To let coroutine proceed with execution return false. keepWaiting property is queried each frame after MonoBehaviour.Update and before MonoBehaviour.LateUpdate.

CustomYieldInstruction让你实现自定义中断指令来暂停协程执行,直到事件发生。自定义中断指令只是另一种运行的协程。要实现这个,需要继承自CustomYieldInstruction类,并重写keepWaiting属性。保持协程暂停返回true,协调继续执行返回false。keepWaiting被查询是在MonoBehaviour.Update之后,在MonoBehaviour.LateUpdate之前。

C#:

using UnityEngine;
 
// Implementation of WaitWhile yield instruction. This can be later used as:
// yield return new WaitWhile(() => Princess.isInCastle);
class WaitWhile: CustomYieldInstruction {
	Func<bool> m_Predicate;
 
	public override bool keepWaiting { get { return m_Predicate(); } }
 
	public WaitWhile(Func<bool> predicate) { m_Predicate = predicate; }
}

To have more control and implement more complex yield instructions you can inherit directly from System.Collections.IEnumerator class. In this case, implement MoveNext() method the same way you would implement keepWaiting property. Additionaly to that, you can also return an object in Current property, that will be processed by Unity's coroutine scheduler after executing MoveNext() method. So for example if Current returned another object inheriting from IEnumerator, then current enumerator would be suspended until the returned one has completed.

要更多的控制以及实现更复杂的中断指令,你可以直接继承System.Collections.IEnumerator类。在这种情况下,实现MoveNext()方法,同keepWaiting属性方法。此外,也能返回对象的当前属性,执行 MoveNext() 方法后,将由Unity协程调度处理。因此,例如,如果从IEnumerator继承当前返回其他对象,那么当前enumerator应暂停,直到已完成返回。

C#:

// Same WaitWhile implemented by inheriting from IEnumerator.
class WaitWhile: IEnumerator {
	Func<bool> m_Predicate;
 
	public object Current { get { return null; } }
 
	public bool MoveNext() { return m_Predicate(); }
 
	public void Reset() {}
 
	public WaitWhile(Func<bool> predicate) { m_Predicate = predicate; }
}

Variables 变量

keepWaitingIndicates if coroutine should be kept suspended.
指示协同程序是否应保持暂停。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文