Lives in Unity
Objective: Set up lives for the Player
We will start by creating a lives variable in the Player script. We then create a lives display like the coins using a UI text element and position it above the coins UI element on the screen.
Next in the UIManager we create a serialized private text variable for the lives text element and assign it in the Inspector. We then create a public method to manage lives just like the coins. Inside the Player we update the UIManager lives text element in the Start method.
Now we need to create the logic to reduce the Players lives and respawn after he has fallen off the platform. We start by creating an empty object and calling it RespawnLocation and setting its position the same as the Players start position. Next we need to know when the Player has fallen off. We will use a scaled cube called DeadZone the length of the Y-axis of our scene and turn off the Mesh Renderer and set it to IsTrigger.
We add a Rigidbody to the DeadZone and attach a new script called DeadZone. Before we go to the DeadZone script we need to add the logic in the Player script to reduce the lives. We also want to be able to reload the scene if the Player dies with no lives left. We use the UnityEngine.SceneManagement to allow the scene to reload.
To set up the lives logic we create a public UpdateLives method that takes in an integer variable. This technically isn’t needed right now but if we decide later we want to add extra life collectables this can be used to reduce the lives on death and increase the lives on a collectable. We then change the lives according to the passed variable and make a call to the UIManager to update the lives UI text and then reload the scene if the lives are gone.
Inside the DeadZone script we run an OnTriggerEnter and check if other is the Player. We then get the Players player script and character controller using GetComponent and null check both. Once the Player null check is done we call the Player script and reduce the lives. If the character controller null check passes we disable the character controller as this is needed for when we respawn otherwise the player is moving too fast and doesn’t end up at the respawn position. We set the other(players) transform position to the respawn point position using a serialized GameObject that is assigned to the respawn location GameObject in the Inspector. We then create a coroutine to re-enable the controller after 0.5 seconds and pass the controller to the coroutine.
There is a slight issue with this as when the Player respawns it tries to use the controllers move and triggers warnings. To fix this issue open the Player script and inside the Update method wrap the movement code in a conditional if controller is enabled which prevents the Player accessing or trying to access the controller before it is re-enabled.