Learning Unity — An Introduction To Time In Unity Scripting
In the last article, we looked at a simple example of creating and destroying game objects using Unity scripting. In this article, we will be exploring the use of time in Unity scripts.
Tracking time is a fundamental aspect to modern games. Some things you may want to use time for in your own projects are things like cool downs on player abilities or spawn rates for enemies.
To illustrate an easy example of using time in Unity, we’re going to take our work from the last article and change it so that our game objects get instantiated and destroyed based on time instead of user input.
To do this, we use Unity’s “Time” class and its property “time”. This property gives us the value, in seconds, of how long the application has been running.
All of our work will be done within the “Controller” script we created last time. The first thing we need to do is create a new class level variable to represent when we next want our game object to be instantiated/destroyed.
Time.time is of type float, so our new variable must also be of that type so that we may compare the two. We will want to assign a value to _nextCycle here, as we are going to be comparing it to Time.time immediately. You could set a higher initial value, if you wished to delay activity.
Next we need to replace our user input with a comparison to Time.time.
So now instead of waiting for the user to press the space key, we now are waiting for Time.time (the amount of time our application has been running) to pass our _nextCycle variable. Unless you changed it in your own code, this should happen immediately.
But now we have a problem. Do you see what it is?
Time.time is constantly updating and growing larger with each passing moment. Our variable _nextCycle, on the other hand, is not changing at all. So now once Time.time reaches the value of _nextCycle, our condition is met and all of the code will run every frame — constantly creating and destroying our 3D game object.
How we fix this is by updating the value of _nextCycle every time Time.time reaches it. We can do this anywhere inside the time-based conditional.
With this line, every time _nextCycle is reached we reset its value to two seconds in the future. You could use values other than two, or reset it in any number of other ways, but the important part is to remember that it needs to be in the future. Or, in other words, it needs to be greater than the current value of Time.time.
With this code in place, our script instantiates our game object, does nothing for ~2 seconds, then destroys the object, does nothing again for ~2 seconds, and then the cycle starts over.
And that’s all there is to it! In the next article, we’re going to take our first look at Unity’s physics engine. Until then, good luck and happy coding!