Lifts in Unity
Objective: Create a lift system that pauses 5 seconds before changing floors.
Organize the Lift game objects into different sub-objects by creating Floor, Lift_Landing, Lift_Wall & Lift_Penthouse. In the Floor place all the game objects into a new object called Lift_Platform and create a Cube.
This Cube is the collider for the lift to prevent the player from falling. The mesh renderer is off and box collider is sized to that of the Lift_Platform.
The Floor game object contains the is trigger box collider and the Lift script. Because the Floor is the parent for the lift meshes, the box collider center and size is adjusted, not the transform position and scale. This box collider must be a little larger and above the Cube box collider so that the trigger occurs before the collision. Because Physics.Raycast is used for ground detection the Layer must be Ignore Raycast.
Create three empty game objects to represent the different destinations for the elevator, naming them Floor_1, 2 & 3, and child them to Floor. Set the transform position to be exactly that of the Floor parent object. Floor_2 Y position is about 18 below, and Floor_3 Y position is another 16 below Floor_2.
The Lift script is on the Floor game object and controls the lift behavior, shown below. It uses variables to store floor destinations, _floor1, _floor2, and _floor3, which are assigned in the Floor inspector to respectively, Floor_1, Floor_2, & Floor_3, as shown above. The _target transform contains the current lift destination. While the elevator is paused, _nextFloor stores the destination following the pause. The floats _speed and _delay control, respectively, the rate of movement and the length of the pause at each floor. The bool _goingUp allows the elevator to reverse direction.
Void FixedUpdate is used to move the Floor to the _target using Vector3.MoveTowards. If the Lift has reached the _target, it is assigned to null.
In void Update(), if _target and _nextFloor are null then a new destination is selected, based upon Vector3.Distance from the current position to the different floors , 1 2, & 3. The new destination is stored as _nextFloor, and starts a coroutine LiftMove(). If the lift is at the top or bottom floor it reverses the direction of movement, _goingUp, which is required to decide the next destination upon arriving at _floor2.
The IEnumerator routine, LiftMove, is shown below, which waits for the _delay then assigns _target to be the _nextFloor.
Finally, OnTriggerEnter and OnTriggerExit methods are used to, respectively, parent or unparent the Player to the Floor, providing smooth animation while the Player is on the lift.