Live, die and respawn

How to create a lives and respawn system

In this article we will be creating a lives system, respawn system and death system.

Pseudocode

if the player hits the death zone trigger
then decrease lives
then update the UI lives display
then respawn at respawn point
if lives is zero or less
then reload the current scene

Death Zone

Create a very long box collider to trigger when our player passes through. Make sure the Z is aligned with the rest of the game. Is Trigger is checked. We also tag it as “DeathZone”.

Respawn Point

Empty object with only a transform to hold the position the player should respawn at. We tagged it “Respawn”. Could also be assign through a sersializedfield for example.

UI Lives Text

Created a new UI Text element for our lives text display.

Player Script

We will be reloading the current level if player lives are zero or less. At the top of our script we need to add the SceneManagement library to do that.

using UnityEngine.SceneManagement;

Create a variable to keep track of player lives.

private int _lives = 3;

In Start() update the UI to display the correct lives.

_uIManager.UpdateLivesText(_lives);

If the player hits the DeathZone, which we tagged, then the Death() method will be called.

private void OnTriggerEnter(Collider other)
{
if (other.tag == “DeathZone”)
{
Death();
}
}

The Death() method is called when player falls off.
The current lives will be decreased and the UI will be updated.
If the lives are zero or below the current level will be reloaded.
Else the player position will be changed to the respawn position.
The reason we disable the character controller is while respawning is because when we fall off we move so fast we won’t respawn properly. By disabling and enabling the character controller we can respawn at the desired position.

 public void Death()
{
_lives — ;
_uIManager.UpdateLivesText(_lives);
if (_lives <= 0)
{
//restart game SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
else
{
_controller.enabled = false;
transform.position = GameObject.FindGameObjectWithTag(“Respawn”).transform.position;
_controller.enabled = true;
}
}

UI Manager Script

Using the Inspector we assign our UI Text game object. The public method will be called from our player script, get the lives count and update the text.

[SerializeField] private Text _livesText;public void UpdateLivesText(int livesCount)
{
_livesText.text = “Lives: “ + livesCount;
}

Final Result

--

--

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
Tristan Engel

Tristan Engel

18 Followers

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.