김현준
김현준

Reputation: 1

Can't I use coroutine without a Monobehaviour?

I want to use Coroutine in my script. But I couldn't use "StartCoroutine" because I didn't inherit MonoBehaviour.

As far as I know, I have to inherit Monobehaviour to use Coroutine. But now I can't inherit Monobehaviour. Is there any way to use Coroutine in this situation? The same goes for the Invoke function.

Upvotes: 0

Views: 754

Answers (2)

Nikel
Nikel

Reputation: 116

Coroutine doesn't work without MonoBehaviour, but if you want to use Coroutine in non-MonoBehaviour class you can transmit MonoBehaviour class in constructor or create empty MonoBehaviour to run coroutines on them. It`s will looks like:

pubclic class CoroutineHost : MonoBehaviour{}


public class NonMonoClass
{
   private CoroutineHost _host;
   NonMonoClass()
   { 
       _host = new GameObject("CoroutineHost")
          .AddComponent<CoroutineHost>();
   }

   public void RunYourCoroutine()
   {
       _host.StartCoroutine(nameof(YourCoroutine));
   }

   // Here is should be your coroutine logic
   private IEnumerator YourCoroutine();

    //Finalizer need to destroy  gameobject 
    //when non-mono class will be ready for garbage collection.
   ~NonMonoClass()
   {
       _host.StopAllCoroutines();
       GameObject.Destroy(_host.gameobject);
       _host = null;
   }
}

Upvotes: 1

김대현
김대현

Reputation: 3

I will call what you want to achieve: a Coroutine Management feature and my understanding is that you want to include that feature inside your non-MonoBehaviour class. But thanks to my Remember quote above you cannot do it right now.

But including it in-side a .dll might be possible as a .dll can contain many classes. And you can use Access Modifiers to enforce your rules (the internal modifier is my favorite).

If I were you I would treat Coroutine Management as a separate problem and would build a .dll to handle them separately so that it would not mess up with my game-play business.

Upvotes: 0

Related Questions