PausableObject - Any interest in a tool that can pause coroutines?

I’m not a big fan of the Time.timescale = 0 method of pausing your game. I’d rather pause Components individually, to control exactly what’s going on.

Tonight I’m wrapping up a tool for my own toolbox: PausableObject. Deriving scripts from PausableObject makes it easy to pause and unpause their activity.

You get access to a Paused property (for pausing activity in Update loops), as well as OnPaused() and OnUnpaused() callbacks.

public class TestPausableObject : PausableObject
{
    void Update()
    {
        // just a quick example to show how pausing/unpausing works
        if(Input.GetKeyDown(KeyCode.Space))
        {
            Paused = !Paused;
        }

        if(!Paused)
        {
            // do awesome Update stuff
        }
    }

    protected override void OnPaused ()
    {
       // pause something external, like an animation
    }

    protected override void OnUnpaused ()
    {
        // unpause something external, like an animation
    }
}

Ok sure, but more useful, you get access to a StartPausableCoroutine() method. This will start normal unity Coroutines, but will automatically pause their execution when Paused == true (and resume them when Paused == false).

This coroutine will pause just fine:

public class TestPausableObject : PausableObject
{
    void Awake()
    {
        StartPausableCoroutine(RunPauseTest(10));

        // or

        StartPausableCoroutine("RunPauseTest", 10);
    }

    IEnumerator RunPauseTest(float seconds)
    {
        Debug.Log(Time.timeSinceLevelLoad);

        yield return null;

        Debug.Log(Time.timeSinceLevelLoad);

        yield return new WaitForSeconds(seconds);

        Debug.Log(Time.timeSinceLevelLoad);

        yield return new WaitForEndOfFrame();

        Debug.Log(Time.timeSinceLevelLoad);

        yield return new WaitForFixedUpdate();

        Debug.Log(Time.timeSinceLevelLoad);

        yield return StartPausableCoroutine(WaitForTime(0.1f));

        // (also works with yielding WWW objects)
    }

    IEnumerator WaitForTime(float time)
    {
        yield return new WaitForSeconds(time);
    }
}

I’m wondering if people have written scripts like this into their own project, and if there’d be any general interest for having something like this on the AS.

Cheers!
-Orion

1 Like

I haven’t searched for anything similar and I didn’t have the need yet, but if I do have the need at some point, this seems like a solution I would use for pausing.

A question for anyone: How do you currently handle pausing in your projects? Timescale = 0, or have you rolled your own method?

Thanks!
Orion