Hey there, Gamers and Game Makers!
In this week's blog, we're going to continue our Platformer Tutorial series by learning how to change levels. For example, you reach the end of one level and want to load the next.
To start off, I've created a second very basic scene as we'll actually need a second scene to change to in order to see our script working. I've also added the new scene to the build settings so that it will load.
As you can see in our original scene, I've added a sign or checkpoint of sorts. This will act as our end of level marker. The idea being that once the player reaches this point, the next level will load.
The next thing we want to do is create a new tag for our marker. I've decided to call mine loadLevel but it can be whatever you want. While you're setting tags, make sure the player is set to the player tag while you're at it.
Next create a new C# script called ChangeLevel and open it in Mono Develop. As we're going to be changing scenes, we'll need to import the SceneManagement library. To do this, go up to the top of your script and under the using UnityEngine; line type using UnityEngine.SceneManagement;
Now we want to create a public string called levelName. The reason for this is so we don't have to hard code the name of our level which if we did would mean we would need a script for every single level change which wouldn't be practical. This variable will allow us to enter the name of the level we want to load in the unity editor.
Now we'll create a private void of OnTriggerEnter2D. It's very important you don't forget to add the 2D as we are working on a 2D game. Otherwise unity will assume you are looking for the trigger event of a 3D object. In the parameters field type, Collider2D and the tag you assigned your marker. In my case it's loadLevel.
We then need an if statement to actually check for the collision. We're going to use the CompareTag method to compare the loadLevel tag to that of the player. If the marker detects a collision from an object with the player tag, then load the scene. Otherwise it's simply ignored.
Save your script and back in the Unity editor assign the script to your marker. Give the marker a 2D collider and set it to is trigger. Type in the name of the scene you want to load in the Level Name field of the script component. Save your scene changes and now if you play it you should be able to collide with the marker and load the next scene.
Until next time!