A simple cooldown system in Unity
In my last article, I went over creating lasers for the Player. The rapid fire aspect could make for a cool powerup but for now, let’s look into implementing a simple rate of fire system.
There are a couple of ways to implement a cooldown system, we’re going to look at using Unity’s Time class to do it — I’ll look at co-routines in another article.
Considering the functionality of the cooldown system —
The Player attempts a shot
If time passed checks out with rate of fire
Allow the shot
By initializing out _lastShot variable with an arbitrary negative number we can ensure that our first shot doesn’t get caught out at the start of the game.
Then each time the Player successfully fires a shot, we reset the _lastShot to the timestamp of when it was fired allowing the rate of fire check to progress.
This is a very simple and basic implementation of a rate of fire cooldown system but also very effective and efficient.