Last active
June 3, 2019 12:49
-
-
Save shane-harper/efaa942d9e2b846c580e71749ac35d55 to your computer and use it in GitHub Desktop.
A class for handling starting and stopping of coroutines. Haven't tried it out yet, seemed like a neat idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using UnityEngine; | |
public interface ICoroutineRunner : IDisposable | |
{ | |
/// <summary> | |
/// The MonoBehaviour running the coroutine | |
/// </summary> | |
MonoBehaviour Runner { get; } | |
/// <summary> | |
/// Set the coroutine runner | |
/// </summary> | |
void SetRunner(MonoBehaviour runner); | |
/// <summary> | |
/// Start a coroutine on the runner. This will stop any already running coroutines | |
/// <exception cref="NullReferenceException">A runner must be set before the coroutine can be run</exception> | |
/// </summary> | |
void Start(IEnumerator coroutine); | |
/// <summary> | |
/// Start a coroutine on the runner. This will stop any already running coroutines and set the runner | |
/// </summary> | |
void Start(IEnumerator coroutine, MonoBehaviour runner); | |
/// <summary> | |
/// Stop the currently running coroutine | |
/// </summary> | |
void Stop(); | |
/// <summary> | |
/// Implementation for IDisposable. Stops the coroutine and sets the runner to null | |
/// </summary> | |
void Dispose(); | |
} | |
public class CoroutineRunner : ICoroutineRunner | |
{ | |
public MonoBehaviour Runner { get; private set; } | |
private Coroutine coroutine; | |
/// <summary> | |
/// Create a new coroutine runner. You will need to set a runner on Start or call SetRunner | |
/// </summary> | |
public CoroutineRunner() | |
{ | |
} | |
/// <summary> | |
/// Create a coroutine runner with the runner already set | |
/// </summary> | |
public CoroutineRunner(MonoBehaviour runner) : this() | |
{ | |
Runner = runner; | |
} | |
public void Start(IEnumerator coroutine) | |
{ | |
if (Runner == null) | |
throw new NullReferenceException("Runner", "Cannot start coroutine, no runner set"); | |
Start(Runner, coroutine); | |
} | |
public void Start(IEnumerator coroutine, MonoBehaviour runner) | |
{ | |
Stop(); | |
Runner = runner; | |
this.coroutine = Runner.StartCoroutine(coroutine); | |
} | |
public void Stop() | |
{ | |
if (Runner != null && coroutine != null) | |
{ | |
Runner.StopCoroutine(coroutine); | |
coroutine = null; | |
} | |
} | |
public void SetRunner(MonoBehaviour runner) | |
{ | |
Runner = runner; | |
} | |
public void Dispose() | |
{ | |
Stop(); | |
Runner = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment