Creating a Lives System in Unity (2.5D Platformer) [2]

This article will cover the second part of this lives system I’ve been working on, for ‘killing’ the player (when they fall off the map) and either respawning the player’s character or reloading the scene accordingly 😙

Objective: Create the logic for killing the player’s character when they fall of the map, for respawning them at a given position, and reloading the scene if they run out of lives.

1. To start with, let’s go and revamp our some of the logic in our Player class to support much of this new functionality. I’m opting for defining a public Transform to effectively store the position I’d like to respawn the player at. Aside from this, we can add a few extra lines into our PlayerDied method, adding in an else statement to handle reloading the current scene (in the event the player’s ran out of lives) and adding in some lines to handle repositioning the player:

The CharacterController component we’re using for the player doesn’t particularly like us trying to suddenly change the player’s position, so we do need to make sure to disable and re-enable it to allow for this respawning functionality. I believe there can sometimes be some issues with re-enabling it too soon, so you might need to create a coroutine with a ‘yield return new WaitForSecondsRealtime([seconds])’ to add in a brief delay for this. I haven’t had any issues personally so will be leaving this as it is for the time being.

2. Now let’s create and define a ‘DeadZone’ script. This is a fairly simple class: we’ll just be using the OnTriggerEnter method to detect whenever the player falls/enters into this object’s collider. It’ll then call the public PlayerDied method, ‘killing’ the player’s character:

3. Head on over into Unity, let it compile, and place this DeadZone on an object with a Collider (ideally a BoxCollider). Stretch and reposition the collider so that the player will end up colliding with it if they fall off the level. Disable any MeshRenderer and set isTrigger on the collider to true.

4. Finally, create and position an empty GameObject and name it something like ‘PlayerRespawnPosition’. Drag this object from the hierarchy into the public _playerStartTransform slot and you should be good to go!

Whenever your player character falls into this ‘DeadZone’ the PlayerDied method will be called and their lives will either be updated and broadcasted or the scene will be reloaded. If the player has some lives left, they should be getting respawned at the PlayerRespawnPosition we created 😉

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store