Hey there, Gamers and Game Makers!
In this week's blog, I'm going to show you quickly how you can load a scene on a collision trigger in Unity.
First off, you'll want to open a blank scene and delete the main camera from it. Now add a plane to act as your floor and add in a first person controller. Next we'ere going to add in a cube object. In the object inspector of the cube be sure to mark it's box collider as "Is Trigger".
Next, we're going to create a new C# script. Open it in visual studio. Once open, remove the default functions that appear. We'll first create a private string variable called loadScene. This will hold the name of whatever scene we wish to load. As it's marked as private, we'll have to add [SerializeField] before it. This forces a private variable to become visible in the object inspector in Unity.
Next we'll create a void OnTriggerEnter. Inside of this we'll add an if statement that will compare the tag of the colliding object with the value it expects. In this case "Player". If it's a match then it returns true and executes the SceneManager.LoadScene and loads the scene that is stored in the loadScene variable.
With our script out of the way, let's head back to the scene editor.
We'll now add this script to our cube. You'll see the loadScene field now appear in the inspector and you can enter the name of the scene you want to load. Once you've entered the name of the scene, make sure that scene and the current scene are added to the build settings. Make sure your first person controller is tagged as "Player". Once you've done so, you'll be able to run the scene and once you collide with the cube,you'll load the next scene specified.
Until next time!