Coroutine?

Is there a way to run coroutines in classes which does not inherit from monobehaviour? Or is there any other way to use yield return null in such a class?

You need a MonoBehaviour to tap into Unity’s Coroutine system. As mentioned by Bonfire Boy the yield syntax is not Unity specific so in theory you could write your own Coroutine scheduler, but there are much easier ways.

Here are two options:

  1. Create an new GameObject and add a MonoBehaviour component to it and use this to call StartCoroutine.
  2. Have a MonoBehaviour in the scene that acts as your Coroutine caller. Use this to start the coroutine.

And here is a sample implementation for the first case:

coroutineHandler = new GameObject("_coroutineHandler");
coroutineHandler.AddComponent<MonoBehaviour>();

coroutineHandler.StartCoroutine(YourCoroutine());

you can’t , the only way to do this is to create another class that inherits from monobehaviour and
inside it create an instant of the class that doesn’t inherit from monobehaviour and call it’s methods from the instant.

Is there a way to run coroutines in classes which does not inherit from monobehaviour?

I’m not sure, but I have a theory:

The StartCoroutine() method is what makes the Coroutines work, but it is non-static, meaning it requires an instance of a MonoBehaviour (or derived) class in order to be called. That said, it’s also public, meaning it can be called by any class that has a reference to that instance.

What I mean is that the following code will possibly work.

using UnityEngine;
using System.Collections;

class Test
{
    MonoBehaviour mono;

    public void StartMyCoroutine()
    {
        mono = new MonoBehaviour();
        mono.StartCoroutine("myCoroutine");
    }

    private IEnumerator myCoroutine()
    {
        while (true)
        {
            //Do stuff...
            yield return null;
        }
    }
}

If the above code doesn’t work, then I’m afraid the answer is a very simple “no :/”.

HOWEVER!

If you’re not on a MonoBehaviour derived class, then Coroutines are probably not what you want. Instead, try using Threading: https://msdn.microsoft.com/en-us/library/aa645740(v=vs.71).aspx


Or is there any other way to use yield return null in such a class?

Yes, since yield is a C# keyword: yield statement - provide the next element in an iterator | Microsoft Learn

You can run any public method in any class as coroutine. You can call a coroutine only from a monobehaviour-class.