Up until this point when we took damage and lost lives but we could not regenerate some of those lives. This forced me to play the game more carefully to see how much score I can rack up. Sometimes I make silly mistakes and eat both of those shots from the enemy causing me to lose 2 lives. Well, today we’ll be creating a health collectable that will regenerate lives if we collect a powerup.
Create a health collectable that heals the player by 1.
Update the visuals of the Player to reflect this.
We’ll be adding to our existing modular powerup system and as always I’ll be starting on the player script since that’s where the magic actually happens and from there we’ll work our way to the actual powerup in the hierarchy.
The Player Logic
Our Health Collectable will be our 5th addition and since our case starts with 0 means our Health Collectable will have an ID of 4. Since the creation of the life system, I’ve also added an extra life so that our player has 4 lives. This is very important to prevent “null” or “IndexOutOfRange” exceptions to creep up later.
After creating a new case, we first need to run an if statement and check if our player lives are less than the max amount of lives (4) before the rest of the code runs. This is to prevent those exceptions I just mentioned. If our lives are less than 4 then we can add one life and update the UI accordingly.
I have 2 damage visual effects to show a visual representation if the lives are getting low, and therefore we also need to include functions to turn those effects off if we get a Health Collectable.
We now need to tell the powerup in our game which powerup to give when the player interacts with it. We have an OntriggerEnter2D event and we’ll add another case to the switch and as our player’s Health Collectable has an ID of 4, our powerup will also have an ID of 4. We’ll need to remember this ID for when we build out the actual powerup.
Creating the Powerup
Like before we need to take an existing powerup and drag it to the hierarchy, then we can unpack the powerup to repurpose it and save it as a new powerup. Once the powerup has been unpacked we can start by renaming it. Although the challenge is called Health Collectable I opted to call it “ExtrLifePowerup” instead. I’ve also replaced the image sprite with an appropriate image that represents a Health Collectable. I’ve also set the ID to 4 to give the player an extra life. Once I was happy with my powerup I dragged it to the prefabs folder and added the prefab to my SpawnManager.
And just like that, we have added to the modular powerup setup in a few easy steps. This again proves how easy it is to create powerups using a modular system.