Skip to main content

Load a new Scene when an object reaches a trigger

You will need two scenes for this task.

https://www.youtube.com/watch?v=hGwLAzGABro&ab\_channel=LearnICTNow

Create a level with a moveable player object on one.

The second will be the scene you wish to change to.

I've created a simple scene with rotating objects (learn how to do this here). With some 3D Text added to the scene.

Next we need to add an object that will become the trigger for switching to the next level. We also need to decide where that will be.

Here I have an end platform. We will place a cube onto this to act as our trigger.

Here you can see the cube added to the end area.

On the object we need to set it's collider to be a trigger.

You might find it useful during testing to move the player object to be closer to the trigger, but not in the trigger.

Create a new script called LoadLevel or similar. This script will be attached to the Trigger and will load the next level when the player contacts it.

Attach the script to the object that is to be the trigger and then open the script in your editor.

We are going to make this script generic so that we can reuse it to load different levels.

Delete the start and update methods.

On line 4 add the SceneManagement package as shown.

Line 8 has us create a public string to store the name of the level. We use this so that we can change this in the Unity Editor.

Line 10 starts the OnTriggerEnter method. This takes a collider object.

On Line 11 we check to see if the object that has collided with the trigger has the tag Player.

If it does we use the SceneManager to load the scene with the name stored in the LevelName field / variable.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LoadLevel : MonoBehaviour
{
public string LevelName;

void OnTriggerEnter(Collider col) {
if(col.CompareTag("Player")) {
SceneManager.LoadScene(LevelName);
}
}
}

Now we need to setup the scenes in Unity.

First select the Trigger and enter the name of the scene to load. In my example it is GameOver.

Next make sure that the player has the Player tag assigned to it.

Now open the Build Settings, File > Build Settings.

Drag the scenes you want to use into the Scenes In Build. If they aren't here Unity won't be able to access them.

The first scene is the one that will be initially loaded. This would be a main menu or title scene usually.

Test your scene.

You should now have a scene that switches when the trigger is hit.

You might also want to disable the mesh renderer to make the trigger invisible.