Ammo System with Pickup

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

Tristan Engel
2 min readJun 28, 2021

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
update()
if fire
if ammo > 0
then current ammo minus 1
else
then out of ammo sfx + UI

Actual Code of ammo system

Part of Update():

if (Input.GetButton("Fire1") && Time.time > _nextFire)
{
FireLaser();
}

FireLaser Method:

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

//instantite laser + Y offset
Instantiate(LaserPrefab, transform.position + _laserOffset, Quaternion.identity);
//laser fire SFX
_audioSource.Play();
//update UI for ammo
_uIManager.UpdateUIAmmo(_currAmmo);
}
else
{
//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":
StartCoroutine(TripleShotCooldown());
break;
case "SpeedUp":
StartCoroutine(SpeedUpCooldown());
break;
case "Shield":
_isShieldActive = true;
//activate shield game object
_shield.SetActive(true);
_shieldHealth = 3;
_shieldSprite.color = Color.cyan;
_uIManager.UpdateUIShield(_shieldHealth);
break;
case "Repair":
Repair();
break;
case "Ammo":
_currAmmo = _maxAmmo;
_uIManager.UpdateUIAmmo(_currAmmo);
break;

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

--

--

Tristan Engel

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