Introducing an Ammo Refill Powerup Into Our 2D Galaxy Shooter in Unity!

Chris Hilton
4 min readAug 20, 2021

--

Objective: To give our player an opportunity to refill their ammo to maximum now that they have a limited supply.

Now that we have created a limited ammo supply feature for the player, we need to provide them with an opportunity to be able to refill their ammo to maximum. Similarly like the previous powerups, we are going to have one spawning randomly. Let’s get started!

Create Sprite Powerup

I have gone ahead and opened an existing sprite in GIMP so that we can alter the text from “Shield” to “Ammo” and also saved 15 copies of this powerup all with different colour text so we can replicate the existing powerups:

I then exported these files as PNG files directly into the assets folder of our 2D Galaxy Shooter.

Creating the Animation

Drag and drop the first ammo powerup sprite into the Hierarchy window and click on this object. From here head down the Animation window and click ‘Create’, create a save file for this animation, I named it Ammo_Refill_Powerup_Anim, and then press ‘record’. Next, drag all the sprites into the window, press ‘play’ so see if it looks good and then press ‘record’ again once you are finished.

Adding Components to Ammo Refill Powerup Prefab

Let’s drag and drop this game object into our powerups prefabs folder:

Let’s add or make changes to the following components:

  1. In the Sprite Renderer component, set the sorting layer to ‘foreground’ and the order in layer to ‘1’.
  2. Add Box Collider 2D — Make sure to tick ‘Is Trigger’ and adjust the box collider around the sprite.
  3. Add ‘Powerups’ script and set the Powerup ID to 3 and drag in the audio clip for the powerup collectable.
  4. Make sure the Animator component has a ‘tick’ in the box and that the controller is attached for the animation clip.

Adjusting Some Scripts

Now we need to open up a couple existing scripts and make some minor adjustments. let’s start with the ‘Powerup’ script and in the OnTriggerEnter2D() method let’s add our powerup to our existing switch statement:

Now let’s head into our ‘SpawnManager’ script and make one tiny change to our Random.Range so that the PowerupID we set for this powerup (3) will be found:

Lastly, within the ‘Player’ script, we need to create the method AmmoRefillActive() that is called from the ‘Powerup’ script which handles setting our ammo count back to it’s maximum:

SpawnManager Game Object

The final step we need to complete is on the Spawn Manager game object. We need to increase its array size from 3 to 4 and we also need to drag the ammo refill powerup prefab into the new slot in the Inspector:

Voila!

--

--