In this article, I will go over how to respawn the player to a location if they fall off the platform and lose a life. I am not going to cover the updating of the Lives UI as it is similar to the coin count UI I wrote in the previous article.
Setting Up Respawn Location
We are going to create an empty gameobject, titled it RespawnPosition, and place it where you want the player to respawn.
We will declare a Tranform variable to hold the position of this respawn position and give a serizalized field attribute.
Assign the RespawnPosition game object in the Inspector. Now, we have access to that position.
Detecting Player Fall
I am going to two ways of detecting when the player falls off the platforms. The first way is using the player’s Y position and once it passes a certain point, we will respawn the player and take a life.
The other way is to create a Cube game object and we will call it the DeadZone.
Lets turn off the Mesh Renderer, so this game object isn’t visible. We are going to turn on the Trigger in the Box Collider to detect when the player falls into it. Next, create a script for the DeadZone.
Declare a Transform variable to hold the spawn position game object and assign it inn the Inspector.
In an OnTriggerEnter, we check to see if the other is the player and create a local player class variable and get the player component. We need this, so we can use the LoseLife function from the player script.
At this moment if we tried to set the player’s position to the spawn position, nothing will happen because the player is falling too fast and the script cannot keep up. So, we are going to turn off the characterController to stop the player’s movement and turn it back on when the player has been respawned.
All of this is still happening in the OnTriggerEnter method. First, we will create a local CharacterController class variable and get the CharacterController component. Next, we will set the enabled to false, turing it off, then set the player’s position to the spawn position. Lastly, we need to turn the CharacterController back on, but we need to wait for a split second for the script to catch the Trigger. Using a coroutine, pass in a CharacterController parameter, and return a new WaitForSeconsd before setting the enabled back to true. You will start this coroutine after the player has been repositioned to the spawn position.
The first method requires less lines of code, but it is not as customizable since the DeadZone is a constant y position across the level. The second method requires more lines of code, but since it is a game object, it can be prefabbed and you have multiple dead zones at different positions.
Hopefully this was helpful. Keep coding and cheers!