Player falls off platform and…
Object: Create a system so that when player falls they respawn but lose a life.
In Unity, create a empty game object named Dead_Zone to detect when a player has fallen off the platform. Add a box collider with is trigger checked and a rigidbody with use gravity unchecked. Also create a DeadZone C# script and attach it to the new object.
Select the Dead_Zone game object and adjust the transform scale to X 75, Y 0, Z 15 so that there is a plane underneath the platforms, as shown in the image below. The zone is large to allow for unusual player velocity.
The DeadZone script uses an OnTriggerEnter function to detect if the player has fallen into the dead zone. If other is player then the PlayerDies script is called.
The Player script requires two new variables for _lives and _respawn location, as shown below.
Create an empty game object and set it to the Player’s starting transform position, naming it Respawn_Location, and assign it to _respawn in the inspector for Player.
The PlayerDies() script on the Player requires using UnityEngine.SceneManagement directive to be able to reload the scene, placed at the beginning of the script. The PlayerDies() method on the Player script is shown below and uses GetComponent to grab the character controller of the Player, i.e. controller. The controller, if not null, is then it is disabled to allow the transform.position of the Player to be set to the _respawn point. The controller is then enabled to allow the player to move. A life is deducted from _lives variable. If _lives is now less than one then the game reloads the scene; otherwise, the _uiManager.UpdateLives method passes the number of lives to the UIManager on the Canvas. Check Unity menu file > build settings to make sure the scene is added to the build with index zero and x out without building.
Right click in hierarchy to create a new UI > text object then set it up as shown below.
The UIManager script needs a private Text _livesText variable using a SerializeField to assign Lives_txt in the Canvas’ inspector. The UpdateLives method is shown below and receives the lives from the Player script and updates the _livesText with the current lives, which is displayed on the Canvas.
The _uiManager.UpdateLives(_lives) is also called in void Start() to display the current lives on loading the scene. These scripts on the Dead_Zone, Player and Canvas create a lives and respawn system for the game.
As an aside, if on reloading the scene game objects are grey then set the the mode for light component to realtime on the directional light game object. Next go to the Unity menu Window > Rendering > Lighting, selecting the realtime lightmaps tab, and click generate lighting. This will insure proper lighting of the scene.