Last active
February 15, 2023 15:49
-
-
Save phosphoer/4e0fd613de0ec1a37ecb2db42556f5cd to your computer and use it in GitHub Desktop.
Simple set of coroutine helpers and tweening functions
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 UnityEngine; | |
using System.Collections; | |
public static class Tween | |
{ | |
public static IEnumerator Tween(float duration, System.Action<float> tweenFunc) | |
{ | |
for (float timer = 0; timer < duration; timer += Time.deltaTime) | |
{ | |
tweenFunc?.Invoke(timer / duration); | |
yield return null; | |
} | |
tweenFunc?.Invoke(1); | |
} | |
public static IEnumerator TweenUnscaled(float duration, System.Action<float> tweenFunc) | |
{ | |
for (float timer = 0; timer < duration; timer += Time.unscaledDeltaTime) | |
{ | |
tweenFunc?.Invoke(timer / duration); | |
yield return null; | |
} | |
tweenFunc?.Invoke(1); | |
} | |
public static IEnumerator WaitForTime(float duration) | |
{ | |
for (float timer = 0; timer < duration; timer += Time.deltaTime) | |
{ | |
yield return null; | |
} | |
} | |
public static IEnumerator WaitForTimeUnscaled(float duration) | |
{ | |
for (float timer = 0; timer < duration; timer += Time.unscaledDeltaTime) | |
{ | |
yield return null; | |
} | |
} | |
// Usage: yield return WaitForEvent(f => MyEvent += f, f => MyEvent -= f) | |
public static IEnumerator WaitForEvent(System.Action<System.Action> subscribeDelegate, System.Action<System.Action> unsubscribeDelegate) | |
{ | |
bool invoked = false; | |
System.Action listener = () => invoked = true; | |
subscribeDelegate?.Invoke(listener); | |
// Wait for event | |
while (!invoked) | |
yield return null; | |
unsubscribeDelegate?.Invoke(listener); | |
} | |
public static IEnumerator WaitForEvent<T>(System.Action<System.Action<T>> subscribeDelegate, System.Action<System.Action<T>> unsubscribeDelegate) | |
{ | |
bool invoked = false; | |
System.Action<T> listener = (obj) => invoked = true; | |
subscribeDelegate?.Invoke(listener); | |
// Wait for event | |
while (!invoked) | |
yield return null; | |
unsubscribeDelegate?.Invoke(listener); | |
} | |
public static IEnumerator WaitForEvent<T1, T2>(System.Action<System.Action<T1, T2>> subscribeDelegate, System.Action<System.Action<T1, T2>> unsubscribeDelegate) | |
{ | |
bool invoked = false; | |
System.Action<T1, T2> listener = (a, b) => invoked = true; | |
subscribeDelegate?.Invoke(listener); | |
// Wait for event | |
while (!invoked) | |
yield return null; | |
unsubscribeDelegate?.Invoke(listener); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment