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.

Revisions

  1. Fenikkel created this gist May 16, 2025.
    36 changes: 36 additions & 0 deletions !nfo.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    # Static Coroutine
    <!--
    <p align="center">
    <img src="https://user-images.githubusercontent.com/41298931/283091278-41f7b098-9fe3-4d71-871d-f85751e6b0de.gif" alt="Singleton example">
    </p>
    -->

    &nbsp;
    ## Notes
    Simple tu use and foolproof. It uses abstraction to make it almost invisible on your code and easy to reuse it.


    &nbsp;
    ## Usage

    1. Have the script [`StaticMonoBehaviour`](https://gist.github.com/Fenikkel/046005a2d1dc454fd0c0c965371cbe87#static-monobehaviour) in your project

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

    3. Stop coroutine:
    ```csharp
    StaticCoroutine.Stop(ref _Coroutine);
    ```

    &nbsp;
    ## Compatibility
    - Any Unity version
    - Any pipeline (Build-in, URP, HDRP, etc)

    &nbsp;
    ## Support
    ⭐ Star if you like it
    ❤️️ Follow me for more
    51 changes: 51 additions & 0 deletions Static.Coroutine
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    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();
    }
    }