Almost every game relies on some sort of behind-the-scenes timer, even if you don’t realize it. So let’s dig into Unity’s Engine on Time and make the most basic timer code with an ability cooldown.
Unity3d Time API
Unity’s own documentation is the best source and their UML diagram shown below details out the full order of the in-engine timer. https://docs.unity3d.com/ScriptReference/Time.html
So let’s go over the basics.
Every frame figure out how long it’s been with Time.deltaTime
Check if deltaTime > maxDeltaTime gives us a way to control “how much” time can pass before we say “Hey freeze up a bit”. This is more advance but luckily we can ignore it for the time being.
The engine then adds this deltaTime to Time.time so we know how long the engine has been running and we essentially have the Current Time whenever we call this function.
The engine adds the new time up and sees if we need to run FixedUpdate() now, or if we jump straight to Update().
We will typically use deltaTime for things off frames. The most practical usage is a multiplier on float values to modify movement speed so we always move at the same speed. Without this “deltaTime Offset” our character would move faster in game the higher we could get the FPS.
While we’ll use time for things that need to be timed exactly, activating triggers or preventing activation such as our cooldown system.
The Basic Logic for CoolDown Systems
Cooldown systems can have a lot of moving parts, SFX, animations, just like anything in games. Really the basic logic is fairly simple if we just sit down to write out the pseudocode:
When this gets hard is when you have to connect all the UI, add sound queues, and sanely display potentially 2, 3, or even 10 cooldowns at once in games such as MMOs! But it’s all the same basic structure so we can dive into it as if we can build one we can build the rest!
Basic Firerate Cooldown Code
For example, let’s say we’re writing code so the player can fire a laser, but after firing he has to wait 0.15 seconds before firing again.
We set “_canFireTimer” as the time we fired, offset by, the fire rate.
It’s that easy for simple cooldowns, we could even go as far as making a spell that has a 3-second cooldown by simply setting the fireRate = 3.0f;
Now you can imagine how this can snowball out and there are other manners of managing many spells but they all boil down to this simple concept.
“deltaTime”, used to adjust frame-dependent things such as movement calculations.
“time” which we’ll cache usually with an offset into a float to use elsewhere.