Skip to content

Instantly share code, notes, and snippets.

@raresloth
Last active April 23, 2022 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raresloth/77612fbb998770884a7874e98f8ed848 to your computer and use it in GitHub Desktop.
Save raresloth/77612fbb998770884a7874e98f8ed848 to your computer and use it in GitHub Desktop.
Extension methods for MonoBehaviour that make it easy to schedule a block of code at a given time in Unity
// Runs the block of code at the end of the 10th FixedUpdate from now
myScript.InFixedUpdates(10, delegate
{
DoSomething();
DoSomethingElse();
});
namespace RareSloth
{
public static class MonoBehaviourExtensions
{
// Runs the Callback at the end of the current frame, after GUI rendering
public static Coroutine OnEndOfFrame(this MonoBehaviour self, UnityAction Callback)
{
return self.StartCoroutine(EndOfFrameCoroutine(Callback));
}
static IEnumerator EndOfFrameCoroutine(UnityAction Callback)
{
yield return new WaitForEndOfFrame();
Callback?.Invoke();
}
// Runs the Callback after the next Update completes
public static Coroutine OnUpdate(this MonoBehaviour self, UnityAction Callback)
{
return self.InUpdates(1, Callback);
}
// Runs the Callback after a given number of Updates complete
public static Coroutine InUpdates(this MonoBehaviour self, int updates, UnityAction Callback)
{
return self.StartCoroutine(InUpdatesCoroutine(updates, Callback));
}
static IEnumerator InUpdatesCoroutine(int updates, UnityAction Callback)
{
for (int i = 0; i < updates; i++)
{
yield return null;
}
Callback?.Invoke();
}
// Runs the Callback after the next FixedUpdate completes
public static Coroutine OnFixedUpdate(this MonoBehaviour self, UnityAction Callback)
{
return self.InFixedUpdates(1, Callback);
}
// Runs the Callback after a given number of FixedUpdates complete
public static Coroutine InFixedUpdates(this MonoBehaviour self, int ticks, UnityAction Callback)
{
return self.StartCoroutine(InFixedUpdatesCoroutine(ticks, Callback));
}
static IEnumerator InFixedUpdatesCoroutine(int ticks, UnityAction Callback)
{
for (int i = 0; i < ticks; i++)
{
yield return new WaitForFixedUpdate();
}
Callback?.Invoke();
}
// Runs the Callback after a given number of seconds, after the Update completes
public static Coroutine InSeconds(this MonoBehaviour self, float seconds, UnityAction Callback)
{
return self.StartCoroutine(InSecondsCoroutine(seconds, Callback));
}
static IEnumerator InSecondsCoroutine(float seconds, UnityAction Callback)
{
yield return new WaitForSeconds(seconds);
Callback?.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment