Search Unity

Easily manage running a single coroutine at a time

Discussion in 'Assets and Asset Store' started by bartofzo, Oct 26, 2019.

  1. bartofzo

    bartofzo

    Joined:
    Mar 16, 2017
    Posts:
    151
    Hi,

    I found myself in a situation where I was constantly writing the same code that manages execution of a coroutine that can only run ONE at a time. For example, when fading in an object and halfway a fadeout is triggered by something, the fade in has to stop and the fade out has to take over. So I had to keep references to coroutines everywhere and it made my code messy.

    So I created a script that manages that for you and adds an optional callback for when the coroutine is finished, which is guarantueed to be called, even if the coroutine is 'interrupted'.

    All that's needed now is a single call to StartMonoroutine and the script makes sure that's the only coroutine that's running on that instance of a MonoBehaviour.

    Example:

    Code (CSharp):
    1. using UnityMonoroutine;
    2.  
    3. // Fades in CanvasGroup and then fades it out again
    4. canvasGroup.alpha = 0;
    5. this.StartMonoroutine(canvasGroup.AlphaFade(1, 1),
    6.     () => this.StartMonoroutine(canvasGroup.AlphaFade(0, 1),
    7.     () => Debug.Log("Finished!")));
    Feel free to grab it from my github or contribute to it if you think it can be improved!

    https://github.com/bartofzo/UnityMonoroutine