Unity/C# Challenge 26: Ammo Collectable

Alec Oney
2 min readAug 16, 2021

Challenge: Add a collectable to refill our ammo into our game.

Currently, our ammo count goes down when we fire. What we want to add first is a prefab of our ammo pickup. We make an empty game object, then add a; sprite renderer (with a basic sprite for testing purposes), circle collider 2D (With “Is Trigger” checked), a RigidBody 2D (gravity scale set to 0), and our powerup script. Then, in our prefab, we need to confirm that our Powerup ID within our script is 3:

we can also add the power up sound in

at this point, we are ready to modify our code. First, we want to add a method in our player script that governs setting our ammo to 15:

where, when the script runs, the ammo count resets to 15, and the UI updates to the new ammo count. We then update our Powerup script to include a case for our new Powerup ID:

where our Ammo Reset script runs when the Alert ID is equal to 3.

At this point, we have our ammo reload object and the script necessary to reload our ammo, but we are missing the script necessary to spawn in the ammo reset object. To do that, we change our random range in the SpawnManager script to include our new alert (from 3 to 4 exclusive):

Now, the ammo resupply will spawn in, and the player can collect it:

--

--