How To Create An Elevator In Unity
Elevators can exist in a couple of ways in games. For one example, there is the elevator that once entered, all other things are removed from the scene while another scene is loading in the background; still allowing the player to move around. This can be seen in games like Mass Effect. You could also use the elevator as a trigger that spawns a loading animation of your player riding up/down but just as an animated cinematic. This is seen in games like Metroid Prime.
Similar to the standard moving platform, another option is “in level” elevators that move you from one point of the level to another. This is what we will be making today!
To start you’ll need to create a moving platform. If you are not familiar with how to do this then you can learn by following this link and following along with my previous article: https://adamwreed93.medium.com/creating-moving-platforms-in-unity-b5a816fc101
Once you have a moving platform set with either vertical or horizontal waypoints, you’ll need to set up a trigger collider on a separate game object. This will act as the elevator button. This object does not have to be visible and could just be empty, but with a collider. If your player does not have a rigidbody, then you’ll need to add one to this game object.
Then, create a new C# script and add it to your Elevator Game Object .
The transforms “_origin” and “_target” are the waypoints that you’ll need to set for the elevator to move towards. Be sure to drag and drop them into the serialized fields in the inspector once you complete, and save your script.
Next, create another new script and add this one to the game object that will act as the trigger to call the elevator when the player presses the specified button.
I added a color change to the object which is optional. If you want to do that you will need to create a reference to the objects “Mesh Renderer” as I did in the example above!
OnTriggerStay actually runs off a physics timer every .02 seconds similar to FixedUpdate so you should NEVER try and read player input through that but instead use OnTriggerEnter / OnTriggerExit to manipulate bools that track when the player is within or outside of the collider.