コルーチンを中断するカスタム Yield 命令の基本クラス
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.
このクラスは Unity 5.3 以降で使用できます。
To keep coroutine suspended, return true
. To let coroutine proceed
with execution, return 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"); } }
The following script implements the overridable version of
keepWaiting
. This c# implementation can be used by JS.
In this case make sure this c# script is in a folder such as Plugins
so it is
compiled before the JS script example above.
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 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; } }
詳細に制御して、より複雑な Yield 命令を実装するために System.Collections.IEnumerator
クラスから直接継承できます。この場合、ref::keepWaiting プロパティーを実装するのと同じように MoveNext()
メソッドを実装します。さらに Current
プロパティーでオブジェクトを返すこともできます。 MoveNext()
メソッドを実行後、 Unity のコルーチンスケジューラによって処理されます。ですから例えば Current
が IEnumerator
から継承する別のオブジェクトを返した場合、現在の列挙子はひとつが返ってくるまで中断されます。
// 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; } }
keepWaiting | コルーチンを中断させておく必要がある場合、表示します。 |