Last active
October 2, 2018 16:51
-
-
Save johnsoncodehk/17f05ebbeb1b7966efc4d5a176dd0bd8 to your computer and use it in GitHub Desktop.
Unity Coroutine -> Callback
This file contains hidden or 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
/* | |
* https://gist.github.com/johnsoncodehk/17f05ebbeb1b7966efc4d5a176dd0bd8 | |
*/ | |
using UnityEngine; | |
using System; | |
using System.Collections; | |
public static class YieldReturnExtension | |
{ | |
public static Coroutine YieldReturn<T>(this MonoBehaviour mb, T t, Action onYield, int loopTimes = 1, bool callbackLast = false) | |
{ | |
return mb.YieldReturn(() => t, onYield, loopTimes, callbackLast); | |
} | |
public static Coroutine YieldReturn<T>(this MonoBehaviour mb, T t, Action<T> onYield, int loopTimes = 1, bool callbackLast = false) | |
{ | |
return mb.YieldReturn(() => t, onYield, loopTimes, callbackLast); | |
} | |
public static Coroutine YieldReturn<T>(this MonoBehaviour mb, Func<T> getT, Action onYield, int loopTimes = 1, bool callbackLast = false) | |
{ | |
return mb.StartCoroutine(YieldReturnAsync(getT, t2 => onYield(), loopTimes, callbackLast)); | |
} | |
public static Coroutine YieldReturn<T>(this MonoBehaviour mb, Func<T> getT, Action<T> onYield, int loopTimes = 1, bool callbackLast = false) | |
{ | |
return mb.StartCoroutine(YieldReturnAsync(getT, onYield, loopTimes, callbackLast)); | |
} | |
private static IEnumerator YieldReturnAsync<T>(Func<T> getT, Action<T> onYield, int loopTimes, bool callbackLast) | |
{ | |
while (loopTimes > 0) | |
{ | |
T t = getT(); | |
yield return t; | |
loopTimes--; | |
if (!callbackLast || loopTimes == 0) | |
{ | |
onYield(t); | |
} | |
} | |
} | |
} |
This file contains hidden or 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
/* | |
* https://gist.github.com/johnsoncodehk/17f05ebbeb1b7966efc4d5a176dd0bd8 | |
*/ | |
using UnityEngine; | |
using System; | |
using System.Collections; | |
public static class YieldReturnExtension | |
{ | |
public static Coroutine YieldReturn<T>(this MonoBehaviour mb, T t, Action onYield) | |
{ | |
return mb.StartCoroutine(YieldReturnAsync(t, t2 => onYield())); | |
} | |
public static Coroutine YieldReturn<T>(this MonoBehaviour mb, T t, Action<T> onYield) | |
{ | |
return mb.StartCoroutine(YieldReturnAsync(t, onYield)); | |
} | |
static IEnumerator YieldReturnAsync<T>(T t, Action<T> onYield) | |
{ | |
yield return t; | |
onYield(t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment