What to do if my non-MonoBehavior class METHODS have coroutines?

I’m changing my code structure from messy procedural code to separate classes, using inheritance from a Character class to child classes (“Hero” and “Enemy”).

The problem is that all the code I have written includes coroutines, but non-Monobehaviour classes don’t accept methods such as “StartCoroutine()” or “StopCoroutine()”.

So what should I do with those StartCoroutine() calls and where should I put them?

StartCoroutine is a method of the MonoBehaviour class itself. That’s because when you start a coroutine it actually runs on that MonoBehaviour instance. You have basically two options:

  • Either pass a MonoBehaviour instance as parameter to a normal method of that seperate class and use that instance reference to start your coroutine.
  • Use some sort of MonoBehaviour singleton which you can directly access in your class to run the coroutine on the singleton instance. The CoroutineHelper class i wrote does exactly that and also provides other neat helpers. Though if you only need a singleton to run coroutines on you can simply implement a coroutine host class by using the MonoBehaviourSingleton class and implement an empty class like the following.

Sample CoroutineHost class:

public class CoroutineHost : MonoBehaviourSingleton<CoroutineHost>
{
}

Note that since this is a MonoBehaviour the “CoroutineHost” class need to be in it’s own file named “CoroutineHost”. With this class you can simply “perfix” your StartCoroutine calls with:

CoroutineHost.Instance.StartCoroutine

that’s all. Your coroutines will now run on that singleton instance.