Last active
January 10, 2024 12:11
-
-
Save inoook/505a35b1bd0beebdd23acf87fadd1717 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using UnityEngine; | |
public class TaskExtensions | |
{ | |
/** | |
await TaskExtensions.WaitUntil(() => b, eventActCts.Token); | |
**/ | |
// https://stackoverflow.com/questions/69282112/how-to-do-waituntil-in-async | |
public static async Task WaitUntil(Func<bool> predicate, CancellationToken cancellationToken = default) | |
{ | |
while (!predicate() && !cancellationToken.IsCancellationRequested && Application.isPlaying) | |
{ | |
//Debug.Log("Yield"); | |
await Task.Yield(); | |
cancellationToken.ThrowIfCancellationRequested(); | |
} | |
await Task.CompletedTask; | |
} | |
// Delay | |
public static async Task Delay(int millisecondsDelay, CancellationToken cancellationToken) | |
{ | |
if(cancellationToken == null) { return; } | |
var startTime = Time.time; | |
var elapsedTime = 0f; | |
while (elapsedTime < millisecondsDelay / 1000f && Application.isPlaying) | |
{ | |
//cancellationToken.ThrowIfCancellationRequested(); | |
if (cancellationToken.IsCancellationRequested) | |
{ | |
break; | |
} | |
elapsedTime = Time.time - startTime; | |
await Task.Yield(); | |
} | |
cancellationToken.ThrowIfCancellationRequested(); | |
await Task.CompletedTask; | |
} | |
public static Task Delay(int millisecondsDelay) | |
{ | |
return Delay(millisecondsDelay, CancellationToken.None); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment