Quería implementar algo que funcione de manera similar a yield return new WaitUntil(() => Check()); , pero con una adición adicional. Una vez que se cumple la condición Check() , debe esperar x segundos verificando cada cuadro si la condición sigue siendo verdadera.
Esta es mi implementación:
private IEnumerator CheckCor(float waitTime) { bool checkFlag = true; bool checkFlag2; float whileTime; while (checkFlag) { yield return new WaitUntil(() => Check()); checkFlag2 = true; whileTime = waitTime; while (whileTime > 0) { if (!Check()) { checkFlag2 = false; } whileTime -= Time.deltaTime; yield return null; } if (checkFlag2) { checkFlag = false; } } } donde está Check()
private bool Check();Mi implementación funciona perfectamente bien, pero parece un poco larga.
¿Hay alguna forma más corta de lograr el mismo comportamiento?
(Hacerlo universal también sería una ventaja, por ejemplo, yield return WaitUntilForSeconds(Check(), 3f); , donde Check() es la condición y 3f es el momento de verificar cada cuadro para la condición. Supongo que podría hacerse usando CustomYieldInstruction , pero no estoy seguro de cómo funciona).
No está mal implementar esto como CustomYieldInstruction . Pase el verificador como Func<bool> , mantenga un indicador para recordar si ya ha iniciado el temporizador o no, y restablezca ese indicador si la función de verificación devolvió falso en algún momento. Incluso puede aceptar un Func<float> para llamar cuando el temporizador se restablece con el tiempo restante:
using UnityEngine; public class WaitUntilForSeconds: CustomYieldInstruction { float pauseTime; float timer; bool waitingForFirst; Func<bool> myChecker; Action<float> onInterrupt; bool alwaysTrue; public WaitUntilForSeconds(Func<bool> myChecker, float pauseTime, Action<float> onInterrupt = null) { this.myChecker = myChecker; this.pauseTime = pauseTime; this.onInterrupt = onInterrupt; waitingForFirst = true; } public override bool keepWaiting { get { bool checkThisTurn = myChecker(); if (waitingForFirst) { if (checkThisTurn) { waitingForFirst = false; timer = pauseTime; alwaysTrue = true; } } else { timer -= Time.deltaTime; if (onInterrupt != null && !checkThisTurn && alwaysTrue) { onInterrupt(timer); } alwaysTrue &= checkThisTurn; // Alternate version: Interrupt the timer on false, // and restart the wait // if (!alwaysTrue || timer <= 0) if (timer <= 0) { if (alwaysTrue) { return false; } else { waitingForFirst = true; } } } return true; } } }Entonces, solo puedes usar
yield return new WaitUntilForSeconds(Check, 3f); // or yield return new WaitUntilForSeconds(Check, 3f, (float t) => {Debug.Log($"Interrupted with {t:F3} seconds left!");});Y si necesita un parámetro para el verificador, puede usar una lambda sin parámetros:
yield return new WaitUntilForSeconds(() => Check(Vector3.up), 3f);Y, como es habitual en las lambdas, tenga cuidado con cualquier captura de variable que realice .
Si no desea un CustomYieldInstruction completo, solo usaría otro WaitUntil para la pausa:
private IEnumerator CheckCor(float waitTime) { bool stillWaiting = true; while (stillWaiting) { yield return new WaitUntil(() => Check()); float pauseTime = waitTime; yield return new WaitUntil(() => { pauseTime -= Time.deltaTime; stillWaiting = !Check(); return stillWaiting || pauseTime <= 0; }); if (stillWaiting) { // Stuff when pause is interrupted goes here } } // Stuff after pause goes here }