Ammo System with Pickup

How to limit player fire with an ammo system and refill with collectables

In this article we will create an ammo system to limit how many times the player can shoot. To refill the ammo we will create an ammo collectable.

Ammo system

As always we start off with pseudo code. Then translate that to actual code. After that we will create an UI display for the ammo system. Finally we will create a Ammo power up.

Pseudocode of the ammo system

max ammo = 15
start ()
curr ammo = 15
if fire
if ammo > 0
then current ammo minus 1
then out of ammo sfx + UI

Actual Code of ammo system

Part of Update():

if (Input.GetButton("Fire1") && Time.time > _nextFire)

FireLaser Method:

private void FireLaser()
if (_currAmmo > 0)
_nextFire = Time.time + _fireRate;

//instantite laser + Y offset
Instantiate(LaserPrefab, transform.position + _laserOffset, Quaternion.identity);
//laser fire SFX
//update UI for ammo
//Out of Ammo Sfx
AudioSource.PlayClipAtPoint(_outOfAmmo, Camera.main.transform.position);

(TripleLaser logic is omitted)

Ammo UI

In the UI Manager script we created a handle to the Ammo Text UI Element and assigned it through the Inspector.

Ammo Text UI Element handle

To change the text we use the code:

public void UpdateUIAmmo(int currentAmmo)
_ammoText.text = currentAmmo.ToString();

This method is called from the player script every time the value of ammo changes.

Ammo UI Display in Action

Ammo Collectable

Same as the other powerups we’ve created. In this case when picked up max ammo value overwrites the current ammo value.

Ammo Powerup

The code in bold is the newly added code.

public void PowerUpPickUp(string PowerUpType)
switch (PowerUpType)
case "TripleShot":
case "SpeedUp":
case "Shield":
_isShieldActive = true;
//activate shield game object
_shieldHealth = 3;
_shieldSprite.color = Color.cyan;
case "Repair":
case "Ammo":
_currAmmo = _maxAmmo;

Debug.Log("Default value in switch statement in Player script for PowerUpType");

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.