Unity: Restoring health
We’ve implemented damage already for our player and given them 3 lives. Let’s add a health pick-up that can repair their ship.
The objective with this feature is to restore a single ‘life’ to the player when they collect the health pick-up. This should update the logic as well as the UI and visual damage on the player.
First up, we create the prefab for the collectable. We’ve done this several times already; check out the ammo pick-up here, duplicate it and removed the Ammo.cs script.
We’ll create a similar HealthPickup.cs script so we can, again, keep it apart from other pick-ups:
This is the same as our Ammo.cs script, but it calls RestorHealth(1) on the _player.
In our Player.cs script we add the new RestoreHealth() method which takes an int so that we can adapt this later if we want a full health restore function, for example.
This method restores the logic of the player lives, ensuring it doesn’t go above 3, and sets the damage visualisers to inactive as the player gains lives back. Finally, it updates the UI to reflect the repair.
Both the player Damage and RestoreHealth methods can probably be extracted out to their own class now, and probably refactored to work more efficiently to track player health, but for now this works and will do for our small game. We’ll look into tidying up all of our classes in later articles.
Finally, we need to add our health pickup to our SpawnManager.cs script:
Again, this is almost a copy of the ammo collectable; we assign the prefab in the inspector and set a spawn delay. The coroutine is called in our StartSpawning() method and the collectable will spawn every 15 seconds as it stands. This is for testing and, in reality, we’ll want to carefully tweak both of our pickups to make sure the game is challenging whilst also fair for the player.
So there we have it, our player can now restore their ship’s health with a simple pick-up. We can also easily expand this to include different levels of health pick-up.