Skip to content

Instantly share code, notes, and snippets.

@Fenikkel
Created May 16, 2025 15:37
Show Gist options
  • Save Fenikkel/8fc5efc2648622ba6b4d37751f8adf6e to your computer and use it in GitHub Desktop.
Save Fenikkel/8fc5efc2648622ba6b4d37751f8adf6e to your computer and use it in GitHub Desktop.
Static Coroutine

Static Coroutine

 

Notes

Simple tu use and foolproof. It uses abstraction to make it almost invisible on your code and easy to reuse it.

 

Usage

  1. Have the script StaticMonoBehaviour in your project

  2. Start coroutine:

    StaticCoroutine.Start(ref _Coroutine, ExampleCoroutine(), () => { Debug.Log("Coroutine ended"); });
  1. Stop coroutine:
    StaticCoroutine.Stop(ref _Coroutine);

 

Compatibility

  • Any Unity version
  • Any pipeline (Build-in, URP, HDRP, etc)

 

Support

⭐ Star if you like it
❤️️ Follow me for more

using System;
using System.Collections;
using UnityEngine;
public static class StaticCoroutine
{
public static void Start(ref Coroutine coroutine, IEnumerator iEnumerator, Action onCompleted = null)
{
if (coroutine != null)
{
Debug.LogWarning($"<b>{nameof(coroutine)}</b> is already working. Overriding it.");
Static.MonoBehaviour.StopCoroutine(coroutine);
coroutine = null;
}
if (onCompleted == null)
{
coroutine = Static.MonoBehaviour.StartCoroutine(iEnumerator);
}
else
{
coroutine = Static.MonoBehaviour.StartCoroutine(WrapperCoroutine(iEnumerator, onCompleted));
}
}
private static IEnumerator WrapperCoroutine(IEnumerator iEnumerator, Action onCompleted)
{
yield return iEnumerator;
onCompleted?.Invoke();
}
public static void Stop(ref Coroutine coroutine)
{
if (coroutine == null)
{
Debug.LogWarning("Trying to stop a null reference");
return;
}
Static.MonoBehaviour.StopCoroutine(coroutine);
coroutine = null;
}
public static void StopAllCoroutines()
{
Static.MonoBehaviour.StopAllCoroutines();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment