Version: 2017.2

CustomYieldInstruction

class in UnityEngine

切换到手册

描述

基类,用于暂停协同程序的自定义 yield 指令。

CustomYieldInstruction 可使您实现自定义 yield 指令, 以暂停执行协同程序,直至发生事件为止。在后台,自定义 yield 指令只是另一个正在运行的协同程序。要实现该指令,应继承 CustomYieldInstruction 类,然后重写 keepWaiting 属性。要使 协同程序保持暂停,则返回 /true/。要使协同程序继续执行,则返回 /false/。在 MonoBehaviour.Update 后以及 MonoBehaviour.LateUpdate 前的每一帧均查询 keepWaiting 属性。

该类要求 Unity 5.3 或更高版本。

要使协同程序保持暂停,则返回 /true/。要使协同程序继续执行, 则返回 /false/。

// Example showing how a CustomYieldInstruction script file
// can be used.  This waits for the left button to go up and then
// waits for the right button to go down.
using System.Collections;
using UnityEngine;

public class ExampleScript : MonoBehaviour { void Update() { if (Input.GetMouseButtonUp(0)) { Debug.Log("Left mouse button up"); StartCoroutine(waitForMouseDown()); } }

public IEnumerator waitForMouseDown() { yield return new WaitForMouseDown(); Debug.Log("Right mouse button pressed"); } }

以下脚本实现 keepWaiting 的可重写 版本。此 c# 实现可由 JS 使用。 在这种情况下,确保此 c# 脚本位于 Plugins 之类的文件夹中,以便使其在 上述 JS 脚本示例之前加以编译。

using UnityEngine;

public class WaitForMouseDown : CustomYieldInstruction { public override bool keepWaiting { get { return !Input.GetMouseButtonDown(1); } }

public WaitForMouseDown() { Debug.Log("Waiting for Mouse right button down"); } }
using System.Collections;
using UnityEngine;
using System;

// Implementation of WaitWhile yield instruction. This can be later used as: // yield return new WaitWhile(() => Princess.isInCastle); class WaitWhile1 : CustomYieldInstruction { Func<bool> m_Predicate;

public override bool keepWaiting { get { return m_Predicate(); } }

public WaitWhile1(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.

using System;
using System.Collections;

// Same WaitWhile implemented by inheriting from IEnumerator. class WaitWhile2 : IEnumerator { Func<bool> m_Predicate;

public object Current { get { return null; } }

public bool MoveNext() { return m_Predicate(); }

public void Reset() {}

public WaitWhile2(Func<bool> predicate) { m_Predicate = predicate; } }

变量

keepWaiting指示协同程序是否应保持暂停。