Skip to content

Instantly share code, notes, and snippets.

@mstevenson
Created January 23, 2016 08:56
Show Gist options
  • Save mstevenson/70046764794c545b6c76 to your computer and use it in GitHub Desktop.
Save mstevenson/70046764794c545b6c76 to your computer and use it in GitHub Desktop.
An alternative to Unity's WaitForSeconds yield instruction that invokes a callback during each Update.
/// <summary>
/// Yield on a DoForSeconds object within a coroutine and the supplied callback method
/// will be invoked during each Unity Update cycle.
///
/// Example: yield return DoForSeconds (1, (elapsed, duration) => { Debug.Log (elapsed/duration); });
/// </summary>
public class DoForSeconds : CustomYieldInstruction
{
public delegate void UpdateCallback (float elapsed, float duration);
float elapsed;
float duration;
UpdateCallback callback;
public DoForSeconds (float duration, UpdateCallback updateMethod)
{
this.duration = duration;
this.callback = updateMethod;
}
public override bool keepWaiting {
get {
elapsed = Mathf.Clamp (elapsed + Time.deltaTime, 0, duration);
callback (elapsed, duration);
return elapsed < duration;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment