Adding an Ammo Collectible

Christian Carter
2 min readJun 26, 2021

--

In the last tutorial you learned how to limit the players ammo. Now it’s time to give them some more ammo. This tutorial will cover how to create an ammo collectible. This is very similar to creating a powerup which you can learn about here. The first thing you need is a sprite for the powerup. You can get this from somewhere or create your own using a pixel editor. I used Piskel.

Once you have the sprite in Unity add it to your scene. We are going to treat this just like a powerup so give it a rigidbody 2D and a box collider 2D. Add the powerup script to it. Set the powerup ID to 3 and give it the powerup audio clip. When you are done put it into the powerup prefab folder.

Next, in the Player script create a CollectAmmo function. Increase the ammo count by 10 or whatever feels good to you. Call the UpdateAmmo function from the UI manager to update the UI.

public void CollectAmmo()
{
_ammoCount += 10;
_uiManager.UpdateAmmo(_ammoCount);
}

Next, in the Powerup script you need to add another case to the switch statement in the OnTriggerEnter2D function. This will be case 3. In it call the player function you just created CollectAmmo.

case 3:
player.CollectAmmo();
break;

Next, go to the SpawnManager script. In the SpawnPowerupRoutine function update the random range for the powerup from 3 to 4. Remember Random.Range does not include the max int so to be able to get 3 you need to set it to 4.

int randomPowerUp = Random.Range(0, 4);

The last thing to do is to update the Spawn_Manager object in the unity editor to add the ammo collectable to the powerups array. Change the size to 4 to add another slot and then put the ammo collectable prefab into the Element 3 slot that was just created.

Now more ammo will appear just like the other powerups.

Good Luck Adventurer!

-Chris

--

--

No responses yet