Objective: Create a cooldown system to handle the shooting feature of the player in a space shooter game with Unity.
Now that we know how to instantiate and destroy gameobjects in Unity using laser prefabs in the space shooter game, we need to handle the time that it takes to the player to shoot again so that the scene doesn’t become an infinite rain of lasers destroying everything it touches.
Creating the cooldown system
First, we need to open the script that controls the behavior of our player:
Then, we need a new pair of variables, one that stores the value in seconds that the player will have to wait until the next shot and another one to store the exact time that enables the shot while the game is running:
Now let’s go to the function that creates the laser prefab instance when the player tries to shoot and let’s update the value of the variable that stores the exact time to enable the next shot:
And finally, to make it work, we need to add the time condition in the Update function, where we wait for the spacebar input to call the shooting function. By adding this condition we’ll make sure that if the current execution time is bigger than the time we store to enable the next shot, we are able to call the shooting function:
Now, if we execute the game in Unity, we’ll see that the lasers have to wait for the fire delay to be shot when the player inputs the spacebar:
As we used SerializeField for the fire delay variable, we can modify in the Unity Editor to test the delay time and choose the one we like for our game.
Understanding the flow
In order to understand the flow between the variables and the execution time of the game we can refer to the next table. Suppose we have the next initial values for the variables:
- _canShoot = -1f
- _fireDelay = 0.5f
The initial value of _canShoot was set to -1 in order to allow the first shot, and then, when the shooting function is executed, the value of _canShoot is set to: the current time in the game + the delay of seconds we choose to apply to enable the next shot.
Note: it’s important to say that the implementation above is one of many that could work for a shooting cooldown system, we could also use coroutines but that’s a topic that I’ll cover in next posts.
And that’s it, you can implement a cooldown for your game! :D. I’ll see you in the next post, where I’ll be showing an introduction to Physics in Unity.