Creating a Health Collectable For Our 2D Galaxy Shooter in Unity!
Objective: To provide the player with a health collectable that replenishes 1 health if collected.
Now that we have provided the player with an ammo refill powerup, it is time we give them an opportunity to collect a player life during the game. Let’s get started with building our powerup in Unity.
Adding Components to Player Life 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:
- In the Sprite Renderer component, set the sorting layer to ‘foreground’ and the order in layer to ‘1’.
- Add Box Collider 2D — Make sure to tick ‘Is Trigger’ and adjust the box collider around the sprite.
- Add ‘Powerups’ script and set the Powerup ID to 4 and drag in the audio clip for the powerup collectable.
Adjusting Some Scripts & Building Some Logic
Now we need to create our logic for the health powerup, and tell it to increase a player life if they have lost one, otherwise if they have full health, don’t do anything. Let’s start in the ‘Powerup’ script and head straight back into our OnTriggerEnter2D() method where we are going to add to the switch statement, similar to the ammo refill powerup:
Next, let’s jump into our ‘Player’ script so we can create the method HealthRefillActive() and check to see if our player has lost a life, if so, increase the players health by 1 and update the sprite images. Else, do nothing.
Finally in our scripts, let’s open the ‘SpawnManager’ so we can again change our max range limit from 4 to 5, and now our player life powerup has a chance at randomly spawning (once we update the Spawn Manager below):
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 4 to 5 and we also need to drag the health powerup prefab into the new slot in the Inspector:
Voila!