Waitforseconds and coroutines in a class not derived from MonoBehavior

Hey guys, i have a class (enemy), and i use new to create them in code. It’s a C# script, not deriving from MonoBehavior, since that makes it not possible to use “new” to create an object of the class.

I’m trying to add a function which would run once per second, and I’ve done it before with starting a coroutine, and using waitforseconds, so that part is all ok.

How can i make this work, either by changing my class to : MonoBehavior (in which case i don’t know how to create objects of the class in code), or perhaps using a separate script that derives from MonoBehavior and only starts the coroutine via a method.

This was very simple when my code was all in one script, but since i’m trying best practices, it’s now somehow much harder to handle the interactions between objects. Newbie stuff, but your help is appreciated nevertheless!

You can create instances of a MonoBehaviour using instantiate or via AddComponenet on the GameObject

Instantiating Prefabs:

AddComponenet:

Aside from that you could create a non MonoBehaviour class that has a method suitable to be called as a coroutine but you will need to call it from a MonoBehaviour e.g. in your update call

StartCoroutine(myClass.Foo());

This assumes myClass is an instance of your class and Foo is your suitable method.

Beyond that you can use BackgroundWorkers and manage your own threads if you want truly multi threaded code however be aware that many aspects of the Unity engine are not thread safe … if you want to get into multi-threading maybe checkout the Job system first as its meant to make such simpler … not sure I agree its simpler but it is safer :slight_smile: