Tuesday, July 15, 2014

The awesome power of coroutines

When I first started learning Unity I saw was introduced to the concept of a coroutine. Coroutine a seemed like a nifty way to cause something to happen later in your script. I scoffed at the idea and built myself custom timers.

There were a couple of reasons I chose not to use coroutines. The first was the complexity. It's far easier to understand what code is doing when you can see everything yourself. The second was a misunderstanding of how coroutines worked. I made the assumption that my code would be just as efficient. After all, how much simpler can you get then updating one float each frame?

So I was doing some research for a question on Unity Answers, when I stumbled across how awesome coroutines actually are.

Coroutines are more efficient then manual timers. This is because Unity handles all of the coroutines on a single event system, with one timer. So where I had one to increment one float per method, Unity has one float that manages all of the coroutines. 

Coroutines also help coding simplicity. No need to check against a timer in you Update loop. In fact well structured coroutines can be set up with a single line of code. In some cases you can eliminate the need for an Update function altogether.

Perhaps the coolest thing about coroutines is they stop running once they are finished. This sounds kind of obvious, but it represents a huge efficiency gain over Update. Take a movement script as an example. The traditional way to code this is to set a bool isMoving. The bool is checked each frame in Update. Each time the bool returns true the movement code executes. Once the target is reached the bool changes to false. However the bool is still checked every frame. Not particularly expensive, true. But do it multiple times on multiple game objects, then run it on an and old mobile phone, and it will all add up.

Contrast this to a coroutine. Once the movement starts there is still an internal check every frame. However as soon as movement finishes, no more overhead. This gets even better when you apply it to a function that gets doesn't execute every frame. 

So that's today's revelation. Still waiting on the computer to get back from the shop, so no progress on any actual games yet...

No comments:

Post a Comment