Unity — Block basic training

Alain Schoovers
3 min readMar 26, 2021

--

Goodmorning recruit. I hope you had some time to rest, now let's get you squared away!

You have a weapon but that does not mean you are ready to use it. Until now there were no restrictions on how fast you can fire but that is over now we are going to introduce you to some trigger discipline.

Cooldown Timers

Now there is no limit to how fast you can fire but we can't have you waste ammunition like that its time to set that rifle to Semi-auto.

Within Unity we can use a cooldown timer to see if enough time has passed since your last shot and if we are allowed to fire once more.

To do this we need to create a variable to keep track of the time the last shot was fired and to see if we can fire again, lets call this _canFire and set it to -1.

Now we need to check against the time that has elapsed and see if that time is more than our _canFire variable, to do this we can check it against Time.time.

Time.time is the amount of time in seconds that the application has been running for.

here we are checking if the value of Time.time is greater than the value of _canFire if it is this is True, because the Time.time starts at 0 and we set our _canFire to -1 this will always be true.

The next step is to link this to our fire behavior we created earlier, we can simply do that by adding this code to the if statement like so.

Now we can only fire when the condition is met great, but there is still a problem. As it now stands we are never updating the _canFire so the Time.time is always greater and thus the condition is always true so let's fix this.

For this to work we need to set _canFire to a value greater than Time.time every time we shoot, we do this by setting _canFire to the value of Time.time plus a fire rate let's say 1.5f whenever we press the space bar.

And there we have it we can now only fire once every 1,5 seconds, way more disciplined.

You have some real talent recruit! Now get back to your barracks and clean that rifle, tomorrow we might give you some real targets to shoot at.

See you in the morning thanks for your time and don't waste all your ammo!

--

--