Sometimes you don’t need a Coroutine.

Esteban Ibarra
2 min readMay 19, 2021

--

“Return Null! Return Null!” The rabbit cried! “The function is over and I have to return null!”

As a Unity developer, whenever we need to do anything time-related like wait a few seconds, a Coroutine is often the first thing we rush to, but is it necessary?

Time.time to the rescue!

While I was finalizing the Galaxy Shooter game, I discovered something horrifying. The Spawner would stop spawning after a certain level! I didn’t discover the cause for sure, but I did guess that the Coroutine was being ended at some point prematurely.

A quick difference between Time.time and Time.deltaTime:

Time.time :The number of seconds from the start of the game. It’s a constantly growing number. Use this when you need to compare time to a variable or wait any amount of time. Use it only in variables, try to avoid using it in functions like Lerp or Transform.Translate where deltaTime is more appropriate.

Time.deltaTime : The time in seconds it took to complete the last frame. This is the one you usually multiply your movement to get steady movement across various platforms.

So how do you do a Coroutines job without using a coroutine? Fortunately, you can do it all yourself using the Update method and Time.time. I took the idea from the enemy waiting to fire its lasers using a variable _canFire, and _fireRate. For spawning, it was the same idea: _canSpawn, and _spawningRate!

a quick look at the code:

We check to see if we’re not in the boss fight,

as well as the asteroid is destroyed.

We then compare Time.time that is greater than _canSpawn, just like the enemy fire code.

Then there’s another check if the player is dead and we need to stop spawning.

After spawning the enemy and keeping track of how many we’ve spawned, we then reset _canSpawn by adding Time.time with the _timeToSpawn time amount. if _timeToSpawn is 5, then that means 5 seconds will pass before Time.time > _canSpawn!

The game then checks to see how many enemies have been spawned and if a certain amount has been reached, the next level is initiated, and _enemiesSpawned is reset to 0 to count up to the next level limit.

After some playtesting, I was getting a constant and steady flow of enemies even after levels 7 and 8 which was the point where the coroutine quit. Mission accomplished! I hope this has helped you consider Time.time as an option for your time-waiting needs!

--

--

Esteban Ibarra
Esteban Ibarra

Written by Esteban Ibarra

cartoonist, game artist, and wanabe gamedev.

No responses yet