Skip to content

Instantly share code, notes, and snippets.

@johnsoncodehk
Last active October 2, 2018 16:51
Show Gist options
  • Save johnsoncodehk/17f05ebbeb1b7966efc4d5a176dd0bd8 to your computer and use it in GitHub Desktop.
Save johnsoncodehk/17f05ebbeb1b7966efc4d5a176dd0bd8 to your computer and use it in GitHub Desktop.
Unity Coroutine -> Callback
/*
* 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);
}
}
}
}
/*
* 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