Creating an Elevator in Unity
Objective: Allow the player to call an elevator if they have collected enough coins. The elevator will wait for them to board before moving back.
We’ll create a trigger collider around our elevator panel. While the player is within the collider, if they press the E key, and the elevator has not already been called, the panel will ask the UIManager how many coins the player has collected. If that amount is greater than or equal to the coins required to use the elevator, the indicator and its light will turn green and the elevator will be called. The _isActivated bool will then be flagged as true, so the player can’t call the elevator again.
If the player did not have enough coins, the script will tell the UIManager to display a message, telling the player how many more coins they need.
The elevator itself works much our moving platform. When the elevator panel call the elevator’s CallElevator method, it sets the target to _pointB and flags _isMoving as true.
In the FixedUpdate method, if _isMoving is true, the elevator will move towards the target. When it is very close to the target, it will stop moving.
When the player gets on the elevator, the elevator will make itself the player’s parent so the player will move with the elevator. It will also set _pointA as its target and begin moving again.
When the player gets off the elevator, the elevator will clear the player’s parent property, freeing it from the elevator’s influence.