Creating a Cooldown
In the space shooter game I’m making, I have currently not set a limit on how often the laser can be fired. Well, there is a limit, and its 60 times per second due to the function being called in the Update method. That feels excessive, and like something someone would exploit to speedrun my game.
This is what it looks like when FireLaser() is being called on every single frame.
Lets bring that down to something a bit more reasonable, only accepting input every 0.15 seconds rather than once per frame. We can do this by creating a few new variables, and utilizing the Time.time function built into Unity.
Time.time counts how long the game has been running, and using some simple code we can turn that into a cooldown system. First we create a variable that stores how long we want in between firing(_fireRate). Then we create a second variable that is updated every time the laser is fired to be equal to Time.time + _fireRate. I called this variable _canFire. Finally, we add another check con our if statement that checks our keypress to enable firing. We simply have it check if Time.time is greater than the newly updated _canFire. This would indicate that the 0.15 seconds had passed since the last firing.
This is what it looks like after. Much more reasonable, I think.
Next, I will be talking about Unity’s physics engine.