Skip to main content

Creating Main Menu – Creating Scenes, Controllers, Main Menu Canvas, and Slicing Sprites

Operating System


Creating Scenes

In the Unity environment you will notice an Untitled object in the Hierarchy area. That is the name of the scenes by default, to change it just simply press ctrl + s and save it as Main Menu.
tut6

Creating Controllers

Now that we have the main menu scene we will now create Controllers for the game. The Controllers are game objects that handle some methods that be needed in the game later. To do that just click GameObject tab, then a drop down will show up. Then in the sub menu click Create Empty, a GameObject will appear in the Hierarchy.
tut7

Before working on the GameObject make sure to reset its transform to avoid conflict in the future.
tut8
Rename your GameObject as Game Controller, then go to the Scripts directory creates a new folder called Game Controllers. Right click the mouse button and select create then choose C# script.
tut9
Save it as GameController. The Game Controller handles all the save data of our game.
Note: To avoid script error make sure the name of your script has no space, because C# is white space sensitive. And make sure to save all Controllers inside the Game Controllers folder to avoid misplaced.

Open you’re newly created Script; you notice that there is already a block code in the script. By default the unity engine already created that part to make the developer at ease.

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class GameController : MonoBehaviour {
  6.  
  7. // Use this for initialization
  8. void Start () {
  9.  
  10. }
  11.  
  12. // Update is called once per frame
  13. void Update () {
  14.  
  15. }
  16. }

Now that everything is ready, we will now do our coding thing. First import these important modules
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;

Write these variables inside the GameController class:

  1. public static GameController instance;
  2.  
  3. public bool isMusicOn;
  4. public bool isGameStartedFirstTime;
  5. public bool[] levels;
  6. public int[] highscore;
  7. public int score;
  8. public int currentLevel;
  9.  
  10. private GameData data;

Then write these blocks of code inside the GameController class.
  1. void Awake(){
  2. CreateInstance ();
  3. }
  4.  
  5. // Use this for initialization
  6. void Start () {
  7. InitializeGameVariables ();
  8. }
  9.  
  10. void CreateInstance(){
  11. if (instance != null) {
  12. Destroy (gameObject);
  13. } else {
  14. instance = this;
  15. DontDestroyOnLoad (gameObject);
  16. }
  17. }
  18.  
  19. void InitializeGameVariables(){
  20. Load ();
  21.  
  22.  
  23. if (data != null) {
  24. isGameStartedFirstTime = data.GetIsGameStartedFirstTime ();
  25. } else {
  26. isGameStartedFirstTime = true;
  27. }
  28.  
  29. if (isGameStartedFirstTime) {
  30. isGameStartedFirstTime = false;
  31. isMusicOn = true;
  32. levels = new bool[15];
  33. highscore = new int[levels.Length];
  34.  
  35. levels [0] = true;
  36. for (int i = 1; i < levels.Length; i++) {
  37. levels [i] = false;
  38. }
  39.  
  40. for (int i = 0; i < highscore.Length; i++) {
  41. highscore [i] = 0;
  42. }
  43.  
  44. data = new GameData ();
  45.  
  46. data.SetIsMusicOn (isMusicOn);
  47. data.SetIsGameStartedFirstTime (isGameStartedFirstTime);
  48. data.SetHighScore (highscore);
  49. data.SetLevels (levels);
  50.  
  51. Save ();
  52.  
  53. Load ();
  54. } else {
  55. isGameStartedFirstTime = data.GetIsGameStartedFirstTime ();
  56. isMusicOn = data.GetIsMusicOn ();
  57. highscore = data.GetHighScore ();
  58. levels = data.GetLevels ();
  59. }
  60.  
  61. }
  62.  
  63. public void Save(){
  64. FileStream file = null;
  65.  
  66. try{
  67. BinaryFormatter bf = new BinaryFormatter();
  68. file = File.Create(Application.persistentDataPath + "/data.dat");
  69.  
  70. if(data != null){
  71. data.SetIsMusicOn(isMusicOn);
  72. data.SetIsGameStartedFirstTime(isGameStartedFirstTime);
  73. data.SetHighScore(highscore);
  74. data.SetLevels(levels);
  75. bf.Serialize(file, data);
  76. }
  77.  
  78. }catch(Exception e){
  79. Debug.LogException (e, this);
  80. }finally{
  81. if(file != null){
  82. file.Close ();
  83. }
  84. }
  85. }
  86.  
  87. public void Load(){
  88. FileStream file = null;
  89.  
  90. try{
  91. BinaryFormatter bf = new BinaryFormatter();
  92. file = File.Open(Application.persistentDataPath + "/data.dat", FileMode.Open);
  93. data = bf.Deserialize(file) as GameData;
  94.  
  95. }catch(Exception e){
  96. Debug.LogException (e, this);
  97. }finally{
  98. if(file != null){
  99. file.Close ();
  100. }
  101. }
  102. }
  103. }
  104.  
  105. [Serializable]
  106. class GameData{
  107. private bool isGameStartedFirstTime;
  108. private bool isMusicOn;
  109. private bool[] levels;
  110. private int[] highscore;
  111.  
  112. public void SetIsGameStartedFirstTime(bool isGameStartedFirstTime){
  113. this.isGameStartedFirstTime = isGameStartedFirstTime;
  114. }
  115.  
  116. public bool GetIsGameStartedFirstTime(){
  117. return this.isGameStartedFirstTime;
  118. }
  119.  
  120. public void SetIsMusicOn(bool isMusicOn){
  121. this.isMusicOn = isMusicOn;
  122. }
  123.  
  124. public bool GetIsMusicOn(){
  125. return this.isMusicOn;
  126. }
  127.  
  128. public void SetHighScore(int[] highscore){
  129. this.highscore = highscore;
  130. }
  131.  
  132. public int[] GetHighScore(){
  133. return this.highscore;
  134. }
  135.  
  136. public void SetLevels(bool[] levels){
  137. this.levels = levels;
  138. }
  139.  
  140. public bool[] GetLevels(){
  141. return this.levels;
  142. }

To make this work attach the script to the GameController GameObject as a component, by dragging this to the Game Controller Inspector or by clicking add component then go to script and locate the GameController script.

Creating Music Controller

The Music Controller handles the background sounds of the game; this is where you put your game sound clip as an array. Just like what you did on the Game Controller, create a new GameObject then name it as Music Controller. Then create a new C# script name it as MusicController.
Note: All the needed sounds are already in the Sounds folder.
Inside the Music Controller script, create a certain variable that we will use for our sounds

  1. public static MusicController instance;
  2.  
  3. public AudioClip background, gameplay, loseSound, winSound;
  4.  
  5. [HideInInspector]
  6. public AudioSource audioSource;

Create an instance of the script; this will prevent the script to stop running when going to other scenes.
  1. void CreateInstance(){
  2. if (instance != null) {
  3. Destroy (gameObject);
  4. } else {
  5. instance = this;
  6. DontDestroyOnLoad (gameObject);
  7. }
  8. }

Then create an awake method, a built in method of unity that call any script first when the game started first, call the CreateInstance() inside the awake method.

Create also ang method that initialize all the needed components InitializeVariables(), then write this code inside. After that call the method inside the Awake() method.

  1. void InitializeVariables(){
  2. audioSource = GetComponent<AudioSource> ();
  3. }
  4.  
  5.  
  6.  
  7. void Awake(){
  8. CreateInstance ();
  9. InitializeVariables ();
  10. }

Then write these certain methods to make the sounds work perfectly in the game
  1. // Use this for initialization
  2. void Start () {
  3.  
  4. }
  5.  
  6. // Update is called once per frame
  7. void Update () {
  8.  
  9. }
  10.  
  11. void CreateInstance(){
  12. if (instance != null) {
  13. Destroy (gameObject);
  14. } else {
  15. instance = this;
  16. DontDestroyOnLoad (gameObject);
  17. }
  18. }
  19.  
  20. void InitializeVariables(){
  21. audioSource = GetComponent<AudioSource> ();
  22. }
  23.  
  24.  
  25. public void PlayBgMusic(){
  26. if(background){
  27. audioSource.clip = background;
  28. audioSource.loop = true;
  29. audioSource.Play ();
  30. }
  31. }
  32.  
  33. public void GameplaySound(){
  34. if(gameplay){
  35. audioSource.clip = gameplay;
  36. audioSource.loop = true;
  37. audioSource.Play ();
  38. }
  39. }
  40.  
  41. public void StopAllSounds(){
  42. if(audioSource.isPlaying){
  43. audioSource.Stop ();
  44. }
  45. }

Next you need to attach the script to the Music Controller as a component; it is just the same like you did on Game Controller. After that add a new component called AudioSource. It manages the sounds of the game, and uncheck the Play On Wake because it will be done automatically with the script. Then from the Sounds directory drag all the sound into the corresponding script variables.
tut10

Creating Main Menu Controller

The Main Menu Controller is the one that handles where you start the game, and also trigger some events that necessary needed in the game. To do this just simply creates a new GameObject name it as Main Menu Controller. Create a script and name it as MainMenuController.

Inside the Main Menu Controller script, create a certain variable that we will use. Write this code inside the Main Menu Controller class.

  1. public GameObject settingsPanel, exitPanel;
  2. public Toggle soundToggle;
  3.  
  4. // Use this for initialization
  5. void Start () {
  6. if(GameController.instance != null && MusicController.instance != null){
  7. if (GameController.instance.isMusicOn) {
  8. MusicController.instance.PlayBgMusic ();
  9. soundToggle.isOn = true;
  10. } else {
  11. MusicController.instance.StopAllSounds ();
  12. soundToggle.isOn = false;
  13. }
  14. }
  15. }
  16.  
  17. // Update is called once per frame
  18. void Update () {
  19. if(Input.GetKeyDown(KeyCode.Escape)){
  20. if (exitPanel.activeInHierarchy) {
  21. exitPanel.SetActive (false);
  22. } else {
  23. exitPanel.SetActive (true);
  24. }
  25.  
  26. if (settingsPanel.activeInHierarchy) {
  27. settingsPanel.SetActive (false);
  28. }
  29.  
  30. }
  31. }
  32.  
  33. public void PlayButton(){
  34. SceneManager.LoadScene("Level Menu");
  35. }
  36.  
  37. public void SettingsButton(){
  38. settingsPanel.SetActive (true);
  39. }
  40.  
  41.  
  42. public void CloseSettingsButton(){
  43. settingsPanel.SetActive (false);
  44. }
  45.  
  46. public void SoundToggle(){
  47. if (soundToggle.isOn) {
  48. GameController.instance.isMusicOn = true;
  49. MusicController.instance.PlayBgMusic ();
  50. GameController.instance.Save ();
  51. } else {
  52. GameController.instance.isMusicOn = false;
  53. MusicController.instance.StopAllSounds ();
  54. GameController.instance.Save ();
  55. }
  56. }
  57.  
  58. public void YesButton(){
  59. Application.Quit ();
  60. }
  61.  
  62. public void NoButton(){
  63. exitPanel.SetActive (false);
  64. }

Next you need to attach the script to the inspector of Main Menu Controller as a component.

Note: When using a UI Components in the script you will just need to import some modules

  1. using UnityEngine.SceneManagement;

And for loading some scenes you will also need this
  1. using UnityEngine.UI;

Slicing Sprites

When slicing the sprite sheet into a several images you need to select first your image, then in Sprite Mode choose Multiple after that click Sprite Editor. A new Pop up window will appear from here click the Slice on the menu bar, and then Slice. It will automatically slice the sheet of a sprite.
tut11
tut12

Note: All the needed sprite in the game are already in Sprites folder.

Main Menu Canvas

The Main Menu UI is a GameObject that hold a several Children component. To Create a UI click the GameObject menu then choose UI then Image. You notice that it automatically create a UI Canvas then your image as a child of it, and also a new object will be created automatically called EventSytem.
tut13
Then rename Canvas as Main Menu Canvas, and also Image as Background. In the Main Menu Canvas set the values same as the image shown below.
tut14
To make the Background Image locate your sprite from the Sprites directory then add it to the Background GameObject as a component.
tut15
Now that we have the image we will now add a button Play and Settings. Then remove the child text of button, then locate and add a sprite to their components.
Then attach the Main Menu Controller script to the Play and Settings Button in the RuntimeController.
tut16

tut17

Main Menu Canvas - Exit Panel

We will now create the Exit Panel, exit panel take care of the confirmation prompt that closes the app. Create a panel then name it as Exit Panel Background. And create another panel by just right clicking the GameObject then set its name as Exit Panel and set the components as shown in the inspector below.

Exit Panel Background

tut18

Exit Panel

tut19
Then add a several children (Text, Buttons) for the Exit Panel. Then set the values of each component as shown below.

Text

tut20

Buttons

tut21

Main Menu Canvas - Settings Panel

We will now create the Settings Panel; it takes care of displaying the settings options to change the gameplay. Create a panel then names it as Settings Panel Background. And create another panel by just right clicking the GameObject then set its name as Settings Panel and set the components as shown in the inspector below.

Settings Panel Background

tut22

Settings Panel

tut23

Then add a several children (Text, Toggle, Button) for the Settings Panel. Then set the values of each component as shown below.

Text

tut24

Button

tut25

Toggle

tut26

tut27

tut28

Now that you’re done will the components there is one thing we need to do. Attach all the needed components to the MainController to be able to run the application successfully.

tut29

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.