基类,用于暂停协同程序的自定义 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");
}
}
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; }
}
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.
// 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 | 指示协同程序是否应保持暂停。 |