Day 128 — Setting up the Main Menu
Hey and welcome!
We’re almost finished with the game here, all that’s left to do is to get the main menu created so let’s get to it.
Start things off by creating a new scene under File > New Scene and call it Main_Menu and save it to your scenes folder. Now create a new image object in the hierarchy and call this Background and then click on your Canvas object that gets created automatically. In the inspector make sure that the Canvas Scaler component has the UI Scale Mode set to Scale With Screen Size and that the resolution is 1920 x 1080.
Back in your background object go ahead and add in the BG image which can be found under Sprites > UI > Main_Menu and set the anchor preset to be the stretch on all sides one which looks like this:
Now make the left, right, top and bottom values all 0 and your background image will stretch to fill the whole screen.
Once you have that sorted it’s time to add in all the other images from this Main_Menu folder so go ahead and do that so that you have something like below:
Make sure that the Start, Menu and Quit images there are buttons, the symbol and the title though are just regular images like the background.
Now it’s time for some coding, go ahead and create a new script called MainMenu, attach it to the Canvas object and add in this code for it:
using UnityEngine.SceneManagement;public class MainMenu : MonoBehaviour
{
public void StartButton()
{
SceneManager.LoadScene("Game");
} public void QuitButton()
{
Application.Quit();
}
}
This is just some standard code to load our Game scene and close the application. Back in Unity go ahead and create an OnClick event for your Start and Quit buttons and add in your Canvas object so that you can assign the MainMenu script and bind the relevant functions to each button.
Double check that you have your game scene added to your build settings by checking in File > Build Settings and add it in there if needed.
With that you should now have a functioning main menu for the game!