2D Mobile Game: Main Menu
In this article, we will cover how to create a Main Menu that will have the ability to start and quit the game.
Creating A New Scene
We have been working in one scene that is our game, but the Main Menu will be its own scene. Select File>New Scene to create a new scene.
Make sure to keep things organized in your project file by saving this scene, Main_Menu, into the Scenes folder.
Main Menu Setup
In the Main Menu scene, we will create a Canvas that will allow us to make an interactive UI.
The scale mode should be set to Scale with Screen Size and the resolution set to HD resolution.
The Background Image we are using is sized already to HD resolution. We set it to stretch and make sure the background takes up the Canvas size.
We import the Title Image and set the size to match the Image Size. We are going to anchor this to the center of the Canvas.
We follow similar steps for the accent image.
In the hierarchy, make sure to order images like layers. The first image will be the last layer and as you move down the hierarchy those images are layered onto the previous images.
Lets add a Button and assign the Start Button Image to the source image of the Buttons.
Buttons have default text that we will need to remove, so we only see the Start Button image.
Duplicate the Start Button, swap out the images, and position in the Main Menu scene.
Main Menu Functionality
Now that the Main Menu is setup, we can create a script, Main Menu, that will allow us to call certain functions when buttons are clicked. This script will be attached to the Canvas.
In order to load different scenes in our game, we will need to use the UnityEngine.SceneManagement library.
We will create public methods for the Start Button and Quit Button.
For the start button, we use SceneManger.LoadScene and we can either pass in the scene index or name. This case we will use the name of the scene, “Game”, to load the Game scene when the start button is clicked.
For the Quit Button method, we will use Application.Quit. This will quit the game. This will not work in the editor, but will work when the project has been built.
On the Start Button, we can call a method from script when clicked. We need to pass in the script the method is on and choose the method we want to call (StartButton).
For the Quit Button, we will do the same thing, but call the Quit Button method instead of the Start Button method.
Adding Main Menu Scene
The Main Menu has not been added to the built of the project. Lets go into File and select Build Settings.
We see only the Game scene in the built. Select Add Open Scenes, which will add the Main Menu scene to the build.
The Scenes In Build are indexed with the first scene being loaded first. You can reorder the scenes by click and dragging. We want to have the Main Menu scene be first in the index instead of the game scene.
This is how you can create a Main Menu in Unity. Until next time…Cheers!