Use coroutine inside a non MonoBehaviour class

TonyLi mentions that you can pass a Monobehaviour to start and stop
coroutines inside a instance of a class, but he does not show how you
can do that. He does this

You are can do that with the this keyword. The this keyword will get the current instance of MonoBehaviour.

In this example there’s a tree, which happens to have a component MonoScript:

enter image description here

That particular instance of MonoScript can if it wants (since it’s a c# program) instantiate a general c# class, NonMonoScript:

Class to pass MonoBehaviour from:

public class MonoScript : MonoBehaviour
{
    void Start()
    {
        NonMonoScript  nonMonoScript = new NonMonoScript();
        //Pass MonoBehaviour to non MonoBehaviour class
        nonMonoScript.monoParser(this);
    }
}

Class that receives pass MonoBehaviour instance:

public class NonMonoScript 
{
    public void monoParser(MonoBehaviour mono)
    {
        //We can now use StartCoroutine from MonoBehaviour in a non MonoBehaviour script
        mono.StartCoroutine(testFunction());

       //And also use StopCoroutine function
        mono.StopCoroutine(testFunction());
    }

    IEnumerator testFunction()
    {
        yield return new WaitForSeconds(3f);
        Debug.Log("Test!");
    }
}

You can also store the mono reference from the monoParser function in a local variable to be re-used.

Leave a Comment