Dev Day 54: Creating a Health Power-Up in Unity3D

Objective: Create a Health Power-Up that refills 1 life if the Player’s life count is less than 3, but without exceeding the maximum number of lives allowed.

Step 1: In Unity, drag the Health_Power_Up sprite from the Project window and drop it in the Hierarchy window. Add a Box Collider 2D component, with Is Trigger checked, and add a Rigidbody 2D component, with the Gravity Scale set to 0. Then attach the PowerUp script and assign a value of 4 to the Power Up ID.

Step 2: Drag the Health_Power_Up GameObject from the Hierarchy window into the Power_Up folder within the Prefabs folder in the Project window.

Step 3: In the SpawnManager script, update the randomPowerUp int variable within the SpawnPowerUpRoutine() coroutine to have a random range from 0 to 5, since a new power-up has been added. Then save the script.

Step 4: In the Player script, create a public method called HealthPickupActive(). Within the method, create an if statement, stating that if the Player’s lives count is less than 3, increment the _lives variable value by 1 when this method is called and update the Player’s lives images in the UI. Within this if statement, create a new if statement stating that if the Player’s lives count equals 2 after this method is called, deactivate the _damageVisualLeft GameObject, and if the lives count is equal to 3, deactivate the _damageVisualRight GameObject. This will simulate that the Player has healed when the Health Power-Up is picked up.

Step 5: In the PowerUp script, add a new case, numbered 4, to the switch statement in the OnTriggerEnter2D() method and call the HealthPickupActive() method from the Player script.

Save this script, go back into Unity, and when the Health_Power_Up collides with the damaged Player, the Health will be restored one life at a time.

Unity Developer