Adding Ammo and Health Collectables

For today’s article, I’ll be extending the Power-up system by adding ammo and health drops in the Unity Game. To follow along more closely with the code, please visit https://github.com/hlimbo/Space-Shooter-Tutorial.

Player ship will gain a fixed set of ammo when collecting the Ammo drop and will gain one life

Creating the Prefabs

Both the Health and Ammo Collectables have a Power up, Sprite Renderer, and RigidBody2D components. The only difference between the 2 is their power Up IDs or their power up types where each one is set to their own respective types (e.g. Health goes to Health and Ammo goes to Ammo).

Extending the Power-up System

For the player to respond to these new collectables, I’ve modified the existing Player script and Power up scripts to enable the 2 scripts to communicate with one another when the player receives either the health or ammo pick ups.

Here, I use the OnTriggerEnter2D(Collider2D other) function from Unity’s Monobehaviour to invoke a trigger overlap event and use a switch case statement to pick how to handle the collection of a power-up. In this case, I’m handling how the player script should be affected by exposing public functions in the Player script called AddAmmo(int ammo) and IncrementLives() to allow the PowerUp script to call these functions when a trigger event is detected by Unity.

Lastly, I create public functions in the UiManager script to update the number of lives and the ammo count to display on screen:

In lines 8 through 11, I make a check to see if currentLives is out of bounds to ensure that when the number of lives goes below 0 or above the current number of sprites I have set in the Unity editor (in my case, 4 sprites that represent 0, 1, 2, or 3 lives), then Unity will not throw an out of range exception when it tries to access a value beyond 4 or below 0.

Use 4 sprites to represent 0, 1, 2, or 3 lives in the UI

Thanks for reading :)

Software Engineer