Switching Scenes Using Left Mouse Click C# in Unity2D

There is more than one way to change scenes in Unity. In the previous post, "Moving Between Scenes in Unity2D C# Script" we discussed how to change scene using a 2D box collider to trigger a script to take us to another part of our game.

In this post, you will learn how to set up a left mouse click trigger to switch scenes. This is ideal if you would like a menu screen for your games. These come in handy especially if you are publishing your games on internet portals. 

Lets begin shall we? Same as the last post;

1. First make sure you create two scenes. Name them whatever you like. To keep them organised, I named mine "Level1" & "Level2".

2. Now that you have your scenes created. You need to implement them into your build settings. First go to File, then to build settings. In the image on the left, you can see I have already implemented my scenes in my game. For a fresh game, this should be blank.

The next thing you need to do is to make sure you have your first scene open in Unity. Then select "Add Current".

Now you have to add your second scene. For this, close down your first scene and open your second. Repeat step 2 so you have both of your scenes in the "Scenes In Build" box.

After that's done, click the "X" in the top of the window.

3. Now we need to set up what we want to be clicked to take us to our next scene. For me, I decided to make buttons for mine, These as you can see in the image on the right, "Play Game" & "Controls" using the script below, using the left click on your mouse will take you to different scenes withing the game.




4. Select the button or object you wish to be clicked, then select; Add Component in the inspector, select "Physics 2D" and then select Box Collider 2D and set this to a trigger.




5. Now for the fun part. Create a new C# Script and call it "SwitchScene" and input the following code:
6. Add this code to the empty game object we created earlier.

7. Test the scene and enjoy.




No comments

No comments :

Post a Comment