Player Ammo Count, and Ammo Pickup
Right now, our Player can fire as many Lasers as they want without repercussion. This is fine, but I think having an Ammo counter that depletes would make the game a little more challenging.
In this article we’ll create that Ammo system, as well as a Powerup to replenish Ammo that has been used up!
The Ammo Logic
This is pretty straight forward. Inside our Player script we’ll create variables for the ammoCount, and the maxAmmo. Each time the Player shoots a Laser, decrease the ammoCount by 1.
Then Update the UI element to display as such.
And inside the UIManager script, UpdateAmmo() looks like this:
Ammo UI
We have the Ammo Logic, but we need a UI element for it to interact properly. This can be done in a couple easy steps.
First, create the UI Ammo text in the Canvas to display the Ammo:
And create a reference variable inside the UIManager in which you’ll link this text to:
Now you can properly Update the Ammo:
Collecting more Ammo!
Now we need a way to collect more Ammo or else the Player will be left without Ammo in a matter of seconds!
So, we’ll create a new Ammo Collectible:
I created this Pickup from a Free Pack of Ammo/Bullets in the Unity Asset Store. I used one Ammo Shell and duplicated it creating this Prefab.
It has a RigidBody2D and a BoxCollider2D. As well as the Powerup Script attached:
And now we can edit the Powerup script a bit to include our Ammo Collectible, using Powerup ID 3:
Inside our Player script, we’ll create the AddAmmo() function. I’m using 15 as the amount to add, you can use whatever you feel is correct. You can also create a variable for this amount to change dynamically later on if you choose.
We have an Ammo system now! This can be extended in multiple ways you see fit. It’s up to you to choose what you do with this knowledge!
In the next article, we’ll be creating a Plus 1 Health pickup so that our Player can continue playing the Game longer, itching for that new High Score!