Unity Prototyping: Rate of Fire

Eric Philippot
2 min readJun 30, 2022

--

Flow control in Unity with C#

To create realistic expectations and to adjust against frame rate timing, we need to come up with a way to control how fast a method will update.

As you can see above, without flow control the player can fire all shots within a second. This is because Unity’s Update loop runs every frame. So in order to create a flow rate, or fire rate in this instance, we need to leverage actual time.

To do that, we need to grab Time.time which starts counting in seconds from when the game began.

Code snippet on a colorful background.
Calculate Fire Rate

Here we grabbed Time.time and added a fire rate of 0.2 and stored it in _timeSinceFired. This will shoot almost to 5 shots per second given the time between script cycles.

Next we have to apply it to our fire logic.

Fire Logic

We grab the input to fire and check to see if Time.time (which is seconds since the time the game started) against the last time the fire rate was set. As long as the value of Time.time is more than _timeSinceFired, we can fire again. After that we set _timeSinceFired to Time.time + _fireRate again.

Here I took it further and added a cool down period if too many shots were being fired within a given time.

Full code snippet of the firing function
Fire Cool Down Logic

There is probably a better way to do this that I will figure out later, but here we set a _shotLimit and _shotCount to count shots fired. Now my goal wasn’t to shoot lets say 30 shots and then a cool down, but rather create an overheating effect.

So if _shotCount does not exceed _shotLimit, a bool named canFire will allow you to keep shooting. But once the _shotLimit is exceeded, a coroutine will be set for a 10 second cool down.

If you are not currently firing, an auto cool down will run and lower your shot count as time goes by. 👍

Logic will be refined later on but thank you for reading!

--

--

Eric Philippot

Game and Web Developer with a joined experience of 6 years.