Jump to content

How to load a new level in Unity3D with C#


Recommended Posts

Levels are an essential part of almost every game. When the user beats a certain level they move onto the next one. This keeps the game interactive and fun.


So when programming a game in C# with Unity3D how can this task be accomplished? How do we load a level after a certain event is triggered?


Let's say I have a game object with a collider and I attach the following script to the object.



using UnityEngine;
using System.Collections;
public class TriggerScript : MonoBehaviour {
void OnTriggerEnter(Collider other){
if(other.tag == "Player"){
Application.LoadLevel ("Level_Two");


What the above code will do is detect collisions and then determine if the object that it collided with has the tag of "Player". If this is the case then the command is issued which loads the next level.


The first thing we specified in the code was the two "using" statements. Those have to do with the library we are using in Unity.


The second thing is the class. Everything inside this public class is for the object to which this script is attached. All of our code goes inside there.


The third thing we did was issue the OnTriggerEnter function. This function is built into Unity and is called whenever a game object's trigger is activated (i.e. it is hit by an object).


However it isn't good enough just to detect collisions. We need to make sure that the object it collided with was the player. We do this by creating an if() condition. If the object's tag is equal to "Player" then we run the script to load the next level.


To load a level in Unity you should use the command "Application.LoadLevel();" and specify which level to load inside the parenthesis as shown in the code above. Keep in mind that in order for this level to be loadable it will need to be in the list of levels attached to the game. You can add a level by going into File > Build Settings and adding the scene to the list.


If you have any questions ask them here and I'll be happy to answer them if I can.



Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...