CustomYieldInstruction

         用于挂起协同程序的自定义yield指令的基类。CustomYieldInstruction允许您实现自定义yield指令以暂停协程执行,直到事件发生。在引擎底层,自定义指令只是另一个运行协程。要实现它,请从CustomYieldInstruction类继承 并覆盖keepWaiting属性。保持协程暂停返回true。让coroutine继续执行返回 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");
    }
}
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; }
}

要获得更多控制并实现更复杂的yield指令,您可以直接从System.Collections.IEnumerator类继承。在这种情况下,实现MoveNext()方法的方法与实现keepWaiting属性的方法相同。除此之外,您还可以返回Current属性中的对象,该对象将在执行MoveNext()方法后由Unity的协同调度程序处理。因此,例如,如果Current返回另一个继承自的对象IEnumerator,则当前的枚举器将被挂起,直到返回的对象完成为止。

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; }
}

猜你喜欢

转载自blog.csdn.net/qq_31967569/article/details/83305415
今日推荐