Of course! Here is a comprehensive, step-by-step guide to creating a functional elevator in Unity, complete with the C# script and explanations.
We will create a simple, automatic elevator that moves between two or more floors, waits at each floor, and carries the player with it.
Overview of the Logic
- The Platform: This is the physical object that will move up and down.
- Waypoints: These are invisible points in space that define the location of each floor. The elevator will travel between these points.
- The Controller Script: This script will be attached to the platform. It will manage the movement, know which waypoint to go to next, and handle the wait time at each floor.
- Player Interaction: We'll use a trigger collider to detect when the player steps onto the elevator, making them move along with the platform.
Step 1: Setting Up the Scene
-
Create the Elevator Platform:
- In the Hierarchy window, go to
Create > 3D Object > Cube.
- Rename this
Cube to ElevatorPlatform.
- Use the Scale tool (or the Inspector) to shape it into a flat platform. For example, set the Scale to
X: 4, Y: 0.2, Z: 4.
- Position it where you want the elevator to start (e.g., the ground floor).
-
Create the Waypoints (Floors):
- We need to define where the elevator should stop. We'll use empty GameObjects for this.
- In the Hierarchy, go to
Create > Create Empty.
- Rename this new GameObject to
BottomFloor.
- Position
BottomFloor exactly where you want the center of your elevator platform to be when it's at the bottom. A good trick is to select ElevatorPlatform, copy its position, then select BottomFloor and paste the position.
- Duplicate
BottomFloor (Ctrl+D or Cmd+D) and rename the new one TopFloor.
- Move
TopFloor upwards to the position of the second floor.
- You can create more floors (
MiddleFloor, etc.) if you wish. The script we write will handle any number of waypoints.
-
Create a Player Character (for testing):
- If you don't have one, create a simple player. Go to
Create > 3D Object > Capsule.
- Rename it
Player.
- Add a Rigidbody component to it (
Component > Physics > Rigidbody) so it can be affected by gravity.
- Crucially, tag your player. Select the
Player object, and in the Inspector, click the Tag dropdown and select Player. (If the tag doesn't exist, you can add it).
Step 2: The Elevator Script
Now, let's create the C# script that will control the elevator's logic.
- In the Project window, right-click in the Assets folder and go to
Create > C# Script.
- Name the script
ElevatorController.
- Double-click the script to open it in Visual Studio or your code editor of choice.
Step 3: Writing the Code
Copy and paste the following code into your ElevatorController.cs file. The comments explain what each part of the code does.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ElevatorController : MonoBehaviour
{
// A list of transforms representing the waypoints (floors)
public List<Transform> waypoints;
// The speed at which the elevator moves
public float moveSpeed = 2f;
// The time the elevator waits at each floor
public float waitTime = 3f;
// The index of the current waypoint the elevator is moving towards
private int currentTargetIndex = 0;
// A flag to check if the elevator is currently waiting
private bool isWaiting = false;
void Update()
{
// If there are no waypoints or the elevator is waiting, do nothing
if (waypoints.Count == 0 || isWaiting)
{
return;
}
// Move the elevator towards the current target waypoint
MoveElevator();
}
private void MoveElevator()
{
// Get the position of the current target waypoint
Transform targetWaypoint = waypoints[currentTargetIndex];
// Move the elevator's position towards the target's position
// Vector3.MoveTowards is great for this as it moves at a constant speed
transform.position = Vector3.MoveTowards(transform.position, targetWaypoint.position, moveSpeed * Time.deltaTime);
// Check if the elevator has reached the target waypoint
if (Vector3.Distance(transform.position, targetWaypoint.position) < 0.01f)
{
// If it has reached the destination, start the waiting coroutine
StartCoroutine(WaitAtWaypoint());
}
}
private IEnumerator WaitAtWaypoint()
{
// Set the waiting flag to true to pause movement
isWaiting = true;
// Wait for the specified amount of time
yield return new WaitForSeconds(waitTime);
// Update the target index to the next waypoint in the list
// The modulo operator (%) ensures the index wraps around to 0 when it reaches the end
currentTargetIndex = (currentTargetIndex + 1) % waypoints.Count;
// Set the waiting flag back to false to resume movement
isWaiting = false;
}
// This function is called when another collider enters our trigger
private void OnTriggerEnter(Collider other)
{
// Check if the object that entered is the Player
if (other.CompareTag("Player"))
{
// Make the player a child of the elevator platform.
// This makes the player move with the elevator.
other.transform.SetParent(this.transform);
}
}
// This function is called when a collider exits our trigger
private void OnTriggerExit(Collider other)
{
// Check if the object that exited is the Player
if (other.CompareTag("Player"))
{
// Un-parent the player from the elevator.
// This allows the player to move freely again.
other.transform.SetParent(null);
}
}
}
Step 4: Assembling in the Unity Editor
Now we connect everything together.
-
Configure the Elevator Platform:
- Select the
ElevatorPlatform object in your Hierarchy.
- Add the Script: Drag the
ElevatorController.cs script from your Project window onto the ElevatorPlatform in the Inspector.
- Add Rigidbody: Click
Add Component and add a Rigidbody. Important: In the Rigidbody component, check the box for Is Kinematic. This tells Unity that we will be moving this object with our script, not with physics forces. This prevents strange physics behavior.
- Add Trigger Collider: The platform should already have a
Box Collider. In its component settings in the Inspector, check the box for Is Trigger. This allows other objects (like the player) to pass through it and triggers the OnTriggerEnter and OnTriggerExit functions.
-
Assign the Waypoints:
- Still on the
ElevatorPlatform's Inspector, you will see the Elevator Controller script component. It has a Waypoints list.
- Click the lock icon at the top right of the Inspector to lock it on the
ElevatorPlatform. This makes the next step easier.
- In the Hierarchy, select both
BottomFloor and TopFloor (and any others you made).
- Drag them from the Hierarchy directly onto the word
Waypoints in the Inspector. This will automatically populate the list. You can also set the size of the list manually and drag them in one by one.
- Make sure the order is correct (e.g., Element 0 is
BottomFloor, Element 1 is TopFloor). The elevator will visit them in this order.
- Unlock the Inspector by clicking the lock icon again.
-
Adjust Script Settings:
- In the
Elevator Controller component, you can now set the Move Speed and Wait Time to your liking. A speed of 2 and a wait time of 3 is a good starting point.
You're Done!
Press the Play button. The elevator should start moving towards its first waypoint (BottomFloor), wait, and then move to the TopFloor. If you move your Player capsule onto the platform, it should be carried along for the ride