Unity Guide
Implementing space shooter game features - Ammo limit
A quick review of new features added to a space shooter game in Unity
Objective: Implement a system to limit the ammunition that the player shoots in a space shooter game with Unity.
In the previous post I implemented a health power-up item in my space shooter game with Unity. Now it’s time to implement a system to limit the ammunition, display its stats and provide a way to refill it.
Limiting the ammo
In order to limit the ammunition, let’s start by opening the Player script:
Once opened, let’s create a new variable to store the number of bullets or lasers that the player will be able to carry and shoot:
Then, in the method that gets executed every time the player shoots, let’s add a condition at the start to check if there aren’t lasers available to shoot, and in that case, let’s exit the method:
Now, in case that the player shoots, let’s subtract a unit from the lasers at the end of the method:
Displaying ammo status
With audio
To let the player be aware when it runs out of ammo, let’s add a new audio to the array of the Player script to be played if there’s no ammo:
Let’s add the respective call to play the audio inside the previous condition including the index of the new audio as parameter:
With UI elements
Also, we can use UI elements to display the ammo status, let’s add a new UI element like we have done before:
Using 2 Images and 1 Text element we can make sure to provide the status of the current ammo:
Now let’s open the UI Manager script and create a new public method to update the ammo status:
Then, to be able to update the value on screen, let’s create a new variable to store the reference to the Text element in the canvas:
Now drag the Text element into the UI Manager script component in the canvas:
This way, we’ll be able to modify the text property with the respective value every time that the function is called:
Finally, open the Player script and add the respective call to the UI Manager including the current value of the ammo every time that the player shoots:
And now, if we run the game in Unity, we’ll see that the ammo value is updated when the player shoots:
Provide a way to refill the ammo
Lastly, but not less important, let’s add a new power-up item to refill the ammunition of the player. If you don’t know how to implement a power-up item in your game, you can visit one of my older posts:
Let’s add the sprite of the new power-up item including the respective components that the other power-ups have:
And then, if we run the game again, we’ll be able to refill the ammo when we collect the power-up item:
And that’s it, we implemented a system to limit the ammunition! :D. I’ll see you in the next post, where I’ll be showing more features added to my space shooter game in Unity.