I wrote an article about Coroutines

Maybe you’ll find it useful and interesting:

http://altdevblogaday.com/2011/07/07/unity3d-coroutines-in-detail/

Also, if anyone spots any mistakes in the article, please let me know.

Nicely done. Well written and very informative. I’m certainly no coroutine expert, so it was a good read for me.

Loved the interrupt example; never thought of doing something that way. Thanks for the share!

I’m getting deeper into unity scripting and keep seeing “coroutine” pop up more and more. I’m genuinely interested in knowing what the heck the fuss is about but none of the blogs/articles/tutorials I’ve read explain them in a way I can understand. I’m not much of a programmer so just about everything in this article went over my head.

A regular function (or ‘routine’) starts at the beginning, continues to the end (or until you ‘return’ from it), and then stops. At which point it’s over, gone, finished. Until you call it again, anyway.

This can sometimes be a problem: what if your function is going to take a very long time to run (e.g. it needs to download something from the Internet, or it’s computing something complicated)? While your function is running, no other Unity scripts can run. The game will freeze - maybe only for half a second, but it still becomes a noticable spike. Or maybe, worse: it freezes for several minutes. Can you say “loading screen?”

A coroutine can do something a normal function can’t: It can temporarily pause itself, part-way through, and allow other code to do things, before picking up again later exactly where it left off. This temporary pausing is called ‘yielding’ - kinda like how you might yield to other drivers at a busy intersection. With yields, you don’t have to worry so much about being done quickly - you can do a bit of work and then yield until the next frame, and then everything else in the game has a chance to update, animate, render, etc.

Does that make more sense?

Yeah that helps a little. I hope you don’t mind me derailing your topic for a moment to go into examples. I’m reading Michelle Menard’s textbook right now and there’s this AI script where she briefly states she’s using coroutines because they less taxing on the system but (this is the part I hate the most about the book) doesn’t explain what some of these functions are doing. It might be better to start a new topic about it but I figured I would ask since I have your attention.

Great read I like most people who have posted here have very little experience with coroutines. I look forward to seeing more of your articles.

This is useful for me. I am also a bit confused as to how to use coroutine. Didn’t have chance to use it when i was in javascript and now when i switched over to c#, finding myself learn how to use coroutines. Thanks for the great read. :smile:

Thank you very much. The information presented is slightly above my current level of understanding, though, and it will be difficult to make a breakthrough without a compiling, practical example… My problem with coroutines to this point has been related to pausing a game. I generally implement an event for pausing/unpausing that has a boolean as an argument, and I’d like to be able to do something like this:

PauseButton.Pause += paused => paused ? PauseTheCoroutine() : ResumeTheCoroutine();

Is there an example in your article that could be molded to handle that elegantly? Or can you offer any other code?

Thank you. This has helped me understand a bit more about coroutines (enough to be able to use them anyways).

A nice article, well thought out. Would be interesting how it solves pauses but I guess you’d need an opt-out clause for that.

Nice article! Thanks!

Agree with all above, well written article :slight_smile:

If you want to show me some of her code, I can try and explain it for you. The basic rationale behind coroutines being less taxing is: the engine doesn’t need to call into your code at all while your coroutine has yielded, and the transition from native to managed code (i.e. engine code to your code) is a little more expensive than a regular call. It’s similar to why you shouldn’t have empty Update() functions; you also shouldn’t have an Update() function that immediately returns. If you’re only doing per-frame work some of the time, use a coroutine instead; that way, the rest of the time, Unity doesn’t even need to call your code.

When you pause the game, set Time.timeScale to zero. Aside from this freezing all your physics, animations, etc - it will also freeze the clock used by WaitForSeconds(). Your coroutine can yield for 5 seconds, while it’s yielding the game is paused, saved, and unpaused, and 5 ‘official’ seconds later the coroutine resumes as if nothing happened. So, often, you don’t need to explicitly pause coroutines - they can keep running, waiting for the clock to go back to normal.

And thanks for the kind words, the rest of you :slight_smile:

This is a really interesting idea. Does this mean that starting a coroutine in Start(), which runs forever, is more efficient than using Update()? Or are you saying to trigger a coroutine when an event occurs that then runs until something is false (instead of checking in Update every frame)?

I’ve heard similar ideas such as using a “manager” class which has the Update() call and then sends messages to trigger updates on anything which needs to run. We have a few situations in our game where we need to deal with a lot of updating game objects, so these topics are always interesting to me.

We are using timeScale in our game and have had to manage which items use or ignore it. Do coroutines run every real-time frame unless WaitForSeconds is used? Could I then use something like WaitForSeconds(0.01) to fake slow motion when used with a lower timeScale? (Does that make sense?) Its the different between Update and FixedUpdate if I remember correctly.

Certainly not! It seems like an obvious solution, but I don’t see how it could work in practice, unless your pause menu was simple and unanimated.

Actually, I’ve been using Update in every case where one might use coroutines, because you can easily not have it run by setting .enabled to false, which works great for pausing. But you only get one Update() per class, so it’s not a complete solution unless you are using one class per fake coroutine. I’d love a way to just get as many Updates() as I wanted, which I’m thinking coroutines can do for me; I just don’t know how to put it together yet.

I am guilty of putting returns in my Update() loops to skip updating those when I’m in other areas of the game/app, but since there’s only 3 places where this happens, I don’t figure its a dealbreaker.

It does work in practice. We are doing it.

Can you enable/disable just a component? (I’d just try it but I’m not near my computer right now.) Does SendMessage() still work, or are those ignored as well?