Adjusting the rate of fire in Unity.

Shooting bullets at the speed of, slower than my hands.

Now, a game gives you a gun or some kind of weapon and how fast does it usually let you attack with the weapon? Most of the time, not as fast as you humanly can. There is usually a cooldown before you can attack again, no matter how short it may be. I needed to create this as my current laser that I just made before, shoots as fast as my hands can smash that space bar.

Definitely wouldn't be fair for the enemies would it?

So how do we do this?

Well, as always we have to make Variables. One for my fire rate, another for a time of being able to actually fire. We will get to that in just a moment.

In my shooting code from before, I added in the if statement another requirement using && for if Time.time (Which is the current games running time) is greater than the _canFire variable. (Which at the moment is -1 at start). So when the game starts, whatever seconds the game may have run for, the first time I hit the space bar, Time will be greater than _canFire.

However every time this code is successfully called, I made it so that _canFire changes to the current Time.time + _fireRate, effectively increasing the _canFire as we shoot.

With this I can limit the firing amount of a player and well here is how it looks.

It could use some adjustment but we can easily just change our variable in either the inspector or the script itself.

Remember, limitations are what makes things interesting in games. You can’t have the player be too strong right? Unless it’s a game about that at least.

See you again in the next article!




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Most Unit Testing is Waste — Tests Don’t Improve Quality: Developers Do

30 Days of Code — Day 5

Types are moving to the right

HackWeek in the Age of COVID-19: Making the Best Out of the New Normal

Kubernetes driver for Docker BuildX

Four lessons for web developers

Websocket Under The Hood

How to SharePoint in Outlook like a pro

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Edward Kim

Edward Kim

More from Medium

Adding a camera shake effect

Setting up AI for our Moss Giant!

Using Decals in Unity

P6: Creating a Gritty Office Den