Ammo Collectible | Unity Developer

Derek Anderson
2 min readAug 15, 2023

--

Eventually, the player will run out of ammo and won’t be able to fire off a laser, so let’s create an ammo pickup that will restore the player’s ammo to a maximum amount.

  • There is an animation aspect to this article in order to achieve my desired results, including modifying existing sprites. This article won’t cover that process, but I previously wrote about creating animations that may serve as a reminder.
  1. The first step will be modifying my modular powerup system in my powerup script. The number of powerups, or cases in regards to my code, will be going from 0 to 3, with 3 being the newly created ammo pickup.
switch(powerupID) 
{
case 0:
player.TripleShotActive();
break;
case 1:
player.SpeedBoostActive();
break;
case 2:
player.ShieldActive();
break;
case 3:
player.AmmoCount(15);
break;
default:
Debug.Log("Default Value");
break;
}

2. If the ammo collectible is picked up by the player, the player’s ammo count should equal 15. It will will also update the UI for the ammo count to reflect the change. The changes added below are in my Player script.

public void AmmoCount(int shots)
{
if (shots >= _currentAmmo)
{
_currentAmmo = 15;
}
else
{
_currentAmmo += shots;
}

_uiManager.UpdateAmmo(_currentAmmo);
}

The shots will never go above 15 when the powerup is collected.

3. Make sure your powerup is able to spawn correctly in the SpawnManager script.

 IEnumerator SpawnPowerupRoutine()
{
while (_stopSpawning == false)
{
Vector3 posToSpawn = new Vector3(Random.Range(-8.0f, 8.0f), 7, 0);
int randomPowerup = Random.Range(0, 4);
Instantiate(powerups[randomPowerup], posToSpawn, Quaternion.identity);
yield return new WaitForSeconds(Random.Range(5f, 8f));
}
}

4. The last thing to check is the Spawn Manager game object in the Unity Inspector View. The ammo pickup powerup prefab needs to be attached so it can spawn in your game. Failure to do so will either not spawn the powerup, spawn only your other powerups, or if your spawning methods aren’t correct, will not spawn and prevent the other powerups from spawning (as I experienced).

--

--