Chapter 10: Pausing the Game, Altering Sound, and a Mock Test

In this chapter, we are going to add background music to our game. Then, we will make our music fade in when the level starts, fade out when the level is completed, and stop if the player dies. After that, we will be using all the UI skills we have learned so far to create a pause screen and add some slider components to it (which will be used in the next chapter for volume controls). With the pause screen built, we will make our game pause by freezing the player, the enemies on the screen, bullets, and the moving textures. Also within the pause screen, we will be giving the player the option to resume play or quit so that the game goes back to the title screen with the use of Event Listeners, which we learned about in Chapter 9, Creating a 2D Shop Interface and In-Game HUD. Finally, we will be providing a mini mock test with 20 questions to cover what we have learned from this chapter, as well as previous ones.

By the end of this chapter, we will be able to make changes to the AudioSource component directly within our script. We will know how to make every GameObject stop moving on the screen for our pause screen. Finally, we will know how to create a more fulfilling experience by adding toggle and slider components.

The following topics will be covered in this chapter:

  • Applying and adjusting level music
  • Creating a pause screen
  • Adding a game pause button
  • Mock test

In terms of the Unity Programmer Exam, the next section will label the core objectives that will be covered in this chapter.

Core exam skills covered in this chapter

The following are the core exam skills that will be covered in this chapter:

Programming core interaction:

  • Implement behaviors and interactions of game objects and environments.
  • Identify methods to implement inputs and controls.

Developing application systems:

  • Application interface flow such as menu systems, UI navigation, and application settings.

Programming for scene and environment design:

  • Determine scripts for implementing audio assets.

Technical requirements

The project content for this chapter can be found at https://github.com/PacktPublishing/Unity-Certified-Programmer-Exam-Guide-Second-Edition/tree/main/Chapter_10.

You can download the entirety of each chapter's project files at https://github.com/PacktPublishing/Unity-Certified-Programmer-Exam-Guide-Second-Edition.

All the content for this chapter is held in this chapter's unitypackage file, including a Complete folder that holds all of the work we'll carry out in this chapter.

Check out the following video to see the Code in Action: https://bit.ly/3kjkSBW.

Applying and adjusting level music

In this section, we are going to look at adding background music to our game levels. We will also be updating our scripts so that our music volume changes at different points of the game.

In the following sections, we are going to do the following:

  • Add music to each level.
  • When the player completes the level, make the music fade out.
  • If the player dies, make the music instantly stop.
  • Ensure music does not play in other scenes, only level scenes.

So, let's make a start and add our game music to the level1 scene.

Updating our GameManager prefab

In this section, we are going to update the GameManager game object so that it holds a new game object (called LevelMusic) as a child in the Hierarchy window. We will then assign LevelMusic's AudioSource component and an MP3 fileto play. This kind of setup is ideal for a simple game; otherwise, we potentially run the risk of adding another manager, which is only suitable for a bigger and more complicated game.

To create a game object and add a music file to it, we need to do the following:

  1. In the Unity Editor, open the bootUp scene from the Project window (Assets /Scene).
  2. Right click GameManager in the Hierarchy window and select Audio | Audio Source from the drop-down.
  3. Rename the new game object LevelMusic. The following screenshot shows the game object with its component being created:
Figure 10.1 – Creating an Audio Source Component

Figure 10.1 – Creating an Audio Source Component

With the LevelMusic game object still selected, we can now drag our lvlMusic MP3 file from Assets/Resources/Sound in the Project window into the AudioClip parameter, as shown in the following screenshot:

Figure 10.2 – Add the lvlMusic MP3 to the AudioClip field in the Audio Source Component

Figure 10.2 – Add the lvlMusic MP3 to the AudioClip field in the Audio Source Component

Now is a good time to save our GameManager prefab by selecting it in the Hierarchy window and clicking on Overrides | Apply All in the top-right corner of the Inspector window.

If we now click Play to play the game from the level1 scene, the game will start to play music. This is because, by default, the Audio Source component is set to Play On Awake. This is good, but it won't stop playing until the scene changes, which is enough for most games. However, we want to add control to the music's volume via scripting.

In the next section, we are going to update the ScenesManager script and control when and how our music will be played.

Preparing states for our game music

In this section, we are going to ensure that our game music is no longer set to its default Audio Source setting of Play On Awake. We want the music to be aware of when to play, when to fade the volume down, and when to stop. These three states for the music are connected to the actions of when a game level starts, when the player completes a level, and when the player dies. So, it would be a fair judgment of the three music states to add the music code to the ScenesManager script as it is relatively connected.

To add our three music states (play, stop, and fade down), we need to do the following:

  1. In the Project window, open the ScenesManager script (Assets/Script).
  2. At the top of the ScenesManager script where we have entered our variables, just below the scope of our public enum Scenes property, enter the following enum, along with its three states:

      public MusicMode musicMode;

      public enum MusicMode

      {

        noSound, fadeDown, musicOn

      }

We covered enums back in the Setting up our scene's manager script section in Chapter 3, Managing Scripts and Taking aMock Test; the principles are the same as labeling our states. For our enum, we have assigned it a data type name of MusicMode.

Now that we have our three states labeled, we need to put these into action. We need to make our three states carry out their intended actions:

  • noSound: No music is playing.
  • fadeDown: The music's volume will fade to zero.
  • musicOn: The music will be playing and will be set to its maximum volume.

At various points of the game, we will want these states to be triggered, and the best way of accessing these short sets of states is to use a switch case to funnel out each outcome.

Now, we need to add a switch statement for our three music states.

Still inside the ScenesManager script, we are going to add an IEnumerator that will act on either state. We covered StartCoroutine/IEnumerator in the Setting up our EnemySpawner script section in Chapter 2, Adding and Manipulating Objects.

So, because we are adding an IEnumerator, we also need to add an extra library to support this functionality:

  1. Inside the ScenesManager script, at the very top, add the following library:

    using System.Collections;

  2. Our script now supports coroutines and IEnumerators.

I'm going to place my IEnumerator just outside of the scope of the Update function and name it MusicVolume, where it takes the MusicMode data type, and we will refer to it as musicMode:

IEnumerator MusicVolume(MusicMode musicMode)

  {

  1. Inside the scope of the MusicVolume IEnumerator, we will make a start with our switch statement and take in the reference of one of the three states that would have been sent through from the musicMode reference:

        switch (musicMode)

        {

  2. If musicMode contains the noSound state, then we use GetComponentInChildren<AudioSource>() to grab the only child game object that holds AudioSource, which is the newly created LevelMusic game object.
  3. We then use the Stop function to stop the music and then break out of the case:

    case MusicMode.noSound :

          {

            GetComponentInChildren<AudioSource>().Stop();

            break;

          }

  4. The next case is if musicMode holds the fadeDown state. Here, we grab the reference of the LevelMusic game object and reduce its volume value over time:

    case MusicMode.fadeDown :

          {

            GetComponentInChildren<AudioSource>().volume -=

               Time.deltaTime/3;

            break;

          }

  5. The third and final case is musicOn; inside the case, we first make a check to see whether an audio clip has already been loaded into the AudioSource. If there is no audio clip, we discard the rest of the case; otherwise, we Play the music loaded in and set it to full volume (with 1 being the highest):

    case MusicMode.musicOn :

          {

            if (GetComponentInChildren<AudioSource>().clip != null)

            {

              GetComponentInChildren<AudioSource>().Play();

              GetComponentInChildren<AudioSource>().volume = 1;

            }

            break;

To close the switch statement, we add our yield return with a fraction-of-a-second delay to give our game time to change the settings from the switch statement:

      }

    }

      yield return new WaitForSeconds(0.1f);

  }

Now that we have created our enum musicMode states and set up what each of them will do when triggered in the IEnumerator, we can move on to implementing the coroutines to make changes to the music.

Implementing our game's music states

In this section, we are going to continue making changes to our ScenesManager script and add StartCoroutines to specific parts of our code with the musicMode state, which is where our music's volume is going to change. So, for example, if the player dies in the game, we want the music to stop immediately by using the noSound state.

Let's make a start on this by loading our music into the game level, follow these steps:

  1. In the ScenesManager script, scroll down to the GameTimer method. For the first case, which checks whether the player is on level 1, 2, or 3, add the following if statement:

            if (GetComponentInChildren<AudioSource>().clip ==   null)

            {

              AudioClip lvlMusic = Resources.Load<AudioClip>

                 ("Sound/lvlMusic") as AudioClip;

              GetComponentInChildren<AudioSource>().clip = lvlMusic;

              GetComponentInChildren<AudioSource>().Play();

            }

Our if statement makes a check to see whether the audio clip of our LevelMusic's AudioSource is empty (null). If it doesn't have an audio clip, the if statement will carry out the following roles:

  • Grab our audio file (lvlMusic.mp3) from its folder and store it as an AudioClip data type.
  • Apply the audio clip to the AudioSource component.
  • Run the Play function from AudioSource.

Now that our music plays when we start a level, we need to make it such that when a level is completed, the music fades out. This part is fairly simple as we are in the correct method to fade the game music out when a level is completed.

Scroll down to the //if level is completed comment and add the following line of code to fade the game music out when a level is completed:

StartCoroutine(MusicVolume(MusicMode.fadeDown));

The last thing to do within the switch statement is to add a line of code that resets the audio clip to null as a failsafe:

      default :

      {

        GetComponentInChildren<AudioSource>().clip = null;

        break;

      }

Now, if our GamerTimer method is called and none of the cases (our player isn't on level 1, 2, or 3) apply, our player is likely to be on the title, game over, or bootup scene, which means we will not play any level music.

Now, we will look at how to use StartCoroutines.

Using StartCoroutine with our music states

Now, we need to learn how to stop and start the music, typically when the level is about to start or abruptly ends (typically when the player dies). Still inside ScenesManager, go back to the methods that will need updating so that they can support the music settings. Follow these steps:

The first method we will be updating is ResetScene. Within the scope of the method, enter the following code:

StartCoroutine(MusicVolume(MusicMode.noSound));

This will make a call to the MusicVolume IEnumrator to turn off the music. The following code block shows how the ResetScene method looks after it's been updated:

  public void ResetScene()

  {

    StartCoroutine(MusicVolume(MusicMode.noSound));

    gameTimer = 0;

    SceneManager.LoadScene(GameManager.currentScene);

  }

The next method we are going to update is the NextLevel method. We can start the music at any time, irrespective of where the player is. We can play it whenever we want with the following code:

StartCoroutine(MusicVolume(MusicMode.musicOn));

The following code block shows what the NextLevel method looks like when the code has been updated:

  void NextLevel()

  {

    gameEnding = false;

    gameTimer = 0;

    SceneManager.LoadScene(GameManager.currentScene+1);

      StartCoroutine(MusicVolume(MusicMode.musicOn));

  }

Now, we'll move on to the Start function, which works as a failsafe for starting a scene and to see whether it should be playing music.

Whenever the ScenesManager script is active, it will automatically attempt to play music from our LevelMusic game object's AudioSource component.

If AudioSource doesn't contain a valid AudioClip (no MP3 found), then our code will presume the level the player is on doesn't require music.

The following code block shows the Start function in its entirety with the added StartCoroutine:

    void Start()

   {

      StartCoroutine(MusicVolume(MusicMode.musicOn));

      SceneManager.sceneLoaded += OnSceneLoaded;

   }

The last method to update is OnSceneLoaded. When a level is loaded, we will attempt to turn the music on. The following code block shows the OnSceneLoaded method with the added StartCoroutine at the top:

     private void OnSceneLoaded(Scene aScene, LoadSceneMode aMode)

   {

    StartCoroutine(MusicVolume(MusicMode.musicOn));

    GetComponent<GameManager> ().SetLivesDisplay(GameManager.

        playerLives);

    if (GameObject.Find("score"))

    {

      GameObject.Find("score").GetComponent<Text>().text =

         GetComponent<ScoreManager>().PlayersScore.ToString();

    }

   }

Save the script and the bootUp scene.

Our code for manipulating music is complete for our level scenes.

In this section, we updated our GameManager so that it holds a second game object called LevelMusic. This LevelMusic game object will hold an AudioSource component that can be manipulated when the player starts a level, completes a level, or dies via the ScenesManager script.

In the next section, we will add a pause screen to our game and learn how to adjust the volume of our music and sound effects, and much more.

Creating a pause screen

Currently, we aren't able to pause the game, nor do we have an options screen that allows us to manipulate the settings of the game. In this section, we are going to combine these ideas so that our game is capable of pausing and we will also be able to change the volume of the music and sound effects.

In this section, we are going to do the following:

  • Add a pause button to the top corner of the screen.
  • Create a pause screen.
  • Add the option to resume the game.
  • Add the option to quit the game.
  • Add a slider for music and sound effects.
  • Create and hook up Audio Mixer to both sliders.

The end result of the pause screen can be seen in the following screenshot:

Figure 10.3 – Finalized view of the Pause Screen

Figure 10.3 – Finalized view of the Pause Screen

Let's make a start by focusing on the visuals of the pause screen. Then, we will hook up the sliders and buttons.

To start with the pause UI visuals, we need to do the following:

  1. Load up the level1 scene from the Project window (Assets/Scene).
  2. With the level1 scene loaded, we can now focus on creating some game objects in the Hierarchy window for our pause screen.
  3. Right-click on the Canvas game object in the Hierarchy window and selec t Create Empty from the drop-down list.
  4. Select the newly created game object, right-click it, select Rename from the drop-down, and rename it PauseContainer.

PauseContainer now needs to be scaled to the size of the game screen so that whatever is a child of this game object can be scaled to the correct scale and position.

  1. To make PauseContainer fully scaled to the game screen's proportions, ensure PauseContainer is still selected in the Hierarchy window and set its Rect Transform properties in the Inspector window to the properties shown in the following screenshot:
Figure 10.4 – PauseContainer Rect Transform property values

Figure 10.4 – PauseContainer Rect Transform property values

That's our PauseContainer created and set to hold two main game objects. The first game object will house all of the pause screen's individual buttons and sliders. The second game object is for the pause button in the top-left corner of the screen and will make the game pause and bring the pause controls up.

The following screenshot shows our game with the pause button in the top-left corner of the screen:

Figure 10.5 – Adding a Pause Button to our Game

Figure 10.5 – Adding a Pause Button to our Game

But let's stay focused on the pause screen and its content before we work on the in-game pause button. To create a PauseScreen game object that will house the game objects, we need to repeat a similar procedure for PauseContainer in terms of our Rect Transform properties.

To create and house a PauseScreen game object in PauseContainer, follow these steps:

  1. Right-click the PauseContainer game object in the Hierarchy window.
  2. Select Create Empty from the dropdown.
  3. The new game object will be a child of the PauseContainer game object. Now, let's rename the newly created game object PauseScreen.
  4. Right-click GameObject, select Rename from the drop-down menu, and name it PauseScreen.
  5. With PauseScreen still selected in the Hierarchy window, give its Rect Transform the same settings as PauseContainer has. Use the previous Rect Transform image as a reference.

We can now make a start by filling our PauseScreen game object with its own game objects.

Let's start dimming the screen so that the player isn't distracted when the game is paused.

To create a dim effect, follow these steps:

  1. In the Hierarchy window, right-click the PauseScreen game object and select Create Empty. Then, rename the game object blackOutScreen.
  2. Apply the same Rect Transform properties that you applied to the last two game objects.
  3. Now, we need to add the Image component so that we can cover the screen with a semi-transparent black.
  4. With blackOutScreen still selected, click the Add Component button in the Inspector window and type Image. Once you see the Image component in the drop-down list, select it to add it to blackOutScreen.
  5. The last thing to do for the blackOutScreen component's image property is to set its Color settings to the ones shown in the following screenshot:
Figure 10.6 – Set the blackOutScreen Image Component Color values (RGBA) to the ones in this screenshot

Figure 10.6 – Set the blackOutScreen Image Component Color values (RGBA) to the ones in this screenshot

We will now have a sheet of semi-darkness across the screen.

Now, let's add the Pause text. To do that, follow these steps:

  1. In the Hierarchy window, right-click the PauseScreen game object and select Create Empty. Then rename the game object PauseText.
  2. This time, give PauseText's Rect Transform properties the following values:
Figure 10.7 – Set the PauseText Rect Transform property values to the ones shown in this screenshot

Figure 10.7 – Set the PauseText Rect Transform property values to the ones shown in this screenshot

Next, we need to add the Text component and set its properties for the PauseText game object.

  1. With PauseText still selected, click the Add Component button in the Inspector window and begin to type Text until you can see it in the drop-down list. Once you do, select it.
  2. Change the settings of Text Component to the ones shown in the following screenshot:
Figure 10.8 – Update all of the PauseText Text Component property values to the ones shown in this screenshot

Figure 10.8 – Update all of the PauseText Text Component property values to the ones shown in this screenshot

If you require more information on Text Component, check out the Applying text and images to your scenes section in Chapter 8, Adding Custom Fonts and UI.

The following screenshot shows what the Hierarchy and Scene views currently look like:

Figure 10.9 – The Pause text should look like this

Figure 10.9 – The Pause text should look like this

We have our pause title customized and centered. Now, let's move on to some sliders for the Music and Effects volume settings. We'll make a start on the Music slider and then duplicate it to the other side of the screen for the Effects slider.

Adding a volume UI slider to the Pause screen

In this section, we are going to give the pause screen its title name and create and customize the pause screen volume sliders for our game's music and its sound effects.

To create, customize, and position the Music slider, follow these steps:

  1. Right-click the PauseScreen game object in the Hierarchy window. Then, from the dropdown, select UI, followed by Slider, as shown in the following screenshot:
Figure 10.10 – Add a Slider from the UI dropdown

Figure 10.10 – Add a Slider from the UI dropdown

  1. Select the newly created Slider game object, right-click it, and rename it Music.
  2. Next, position the Music slider by changing its Rect Transform properties to the ones shown in the following screenshot:
Figure 10.11 – Set the Music Rect Transform property values to the ones shown here

Figure 10.11 – Set the Music Rect Transform property values to the ones shown here

We will now change the color of the Music slider's bar to make it look more suited for the pause screen. We'll do this by changing it from light gray to red.

To change the color of the slider, do the following:

  1. Click the arrow to the left of the Music game object in the Hierarchy window to expand the slider's content. Do this again for the Fill Area game object.
  2. Select the Fill game object from the dropdown of the Music game object, as shown in the following screenshot, just as it would look in the Hierarchy window:
Figure 10.12 – Select Fill from the Fill Area dropdown in the Hierarchy window

Figure 10.12 – Select Fill from the Fill Area dropdown in the Hierarchy window

  1. With Fill still selected, in its Inspector window, change the Image component's Color value to red, as shown in the following screenshot:
Figure 10.13 – Change Fill Image Component Color values to the ones shown in this screenshot

Figure 10.13 – Change Fill Image Component Color values to the ones shown in this screenshot

If you still have the Fill game object selected, you can view the slider's red backgroundby adjusting the Value slider at the bottom of the Slider component in the Inspector window, as shown in the following screenshot:

Figure 10.14 – Update the Fill Slider Component values to the ones in this screenshot

Figure 10.14 – Update the Fill Slider Component values to the ones in this screenshot

Also, as shown in the previous screenshot, we need to set the slider's Min Value to -80 and its Max Value to 0. The reason for this is that in the next chapter, these will match the same values as the Audio Mixer.

The Music slider is set to the right size; we just need to tweak the handle so it isn't so stretched and is easier to click or drag with our fingers. Follow these steps to do so:

  1. In the Hierarchy window, expand all of the game object arrows so that we can get access to the Handle game object. Then, select it.
  2. In the Inspector window, tick the Preserve Aspect box under the Image component to stop the Handle game object from looking so stretched.
  3. With Handle still selected, change its Scale in Rect Transform to 3 on all axes.

The following screenshot shows what our handle looks like now:

Figure 10.15 – The handle of the slider has now been visually updated

Figure 10.15 – The handle of the slider has now been visually updated

The Music slider is now set. This means we can move on to the text so that we can label the slider for the player. To give the slider its own UI text, we need to do the following:

  1. In the Hierarchy window, right-click the PauseScreen game object and from the drop-down list, select UI, followed by Text.
  2. Right-click our newly created Text game object and select Rename from the drop-down list. Rename the game object MusicText.
  3. With the MusicText game object still selected, change its Rect Transform to the following values to position and scale the text in the correct location:
Figure 10.16 – Change the values of the MusicText Rect Transform

Figure 10.16 – Change the values of the MusicText Rect Transform

  1. With the MusicText game object still selected in the Inspector window, update the Text component values to the following property values:
Figure 10.17 – Update the MusicText Text Component property values to the ones shown in this screenshot

Figure 10.17 – Update the MusicText Text Component property values to the ones shown in this screenshot

Our pause screen is starting to take shape. The following screenshot shows what we currently have:

Figure 10.18 – We now have a Music Volume Slider

Figure 10.18 – We now have a Music Volume Slider

We can now copy and paste our music text and slider to the other side of the screen and tweak some of its property values so that it will be identified as the sound effects volume bar.

To duplicate and tweak the music text and slider, do the following:

  1. Hold Ctrl (Command on Mac) and select MusicText and Music from the Hierarchy window so that they are highlighted. Then, press D on the keyboard to duplicate the two game objects.
  2. Select the Music (1) game object, right-click it, select Rename from the dropdown, and change its name to Effects.
  3. Select the MusicText (1) game object, right-click it, select Rename from the dropdown, and change its name to EffectsText.
  4. With EffectsText still selected, update its Rect Transform in the Inspector window with the following property values:
Figure 10.19 – Update the EffectsText Rect Transform property values to the ones shown in this screenshot

Figure 10.19 – Update the EffectsText Rect Transform property values to the ones shown in this screenshot

  1. With EffectsText still selected, we can now pay attention to renaming the text. The rest of EffectsText's Text Component properties can remain the same. Simply change the Text field from MUSIC to EFFECTS, as shown in the following screenshot:
Figure 10.20 – Change the EffectsText Text Component text from MUSIC to EFFECTS

Figure 10.20 – Change the EffectsText Text Component text from MUSIC to EFFECTS

Next, we can move our Effects slider over so that it sits below the EFFECTS text in our scene view. To do this, follow these steps:

  1. Select the Effects game object in the Hierarchy window. In the Inspector window, change its Rect Transform properties to the ones shown in the following screenshot:
Figure 10.21 – Update the Effects Rect Transform Component property values

Figure 10.21 – Update the Effects Rect Transform Component property values

We are nearly done with our pause screen in terms of its visual elements. The last two things we have to configure are the Quit and Resume buttons. As with the slider game objects, we can make one, copy and paste it to create a second, and then edit them.

To create and customize a Quit button, do the following:

  1. Right-click the PauseScreen game object in the Hierarchy window and select UI, then Button, from the drop-down list.
  2. With the newly created Button game object, we can rename it to Quit; right-click the Button game object in the Hierarchy window, select Rename from the dropdown, and rename the game object from Button to Quit.
  3. Now, we can put the Quit game object into the correct location and resize it within our PauseScreen game object.
  4. With the Quit game object still selected, change its Rect Transform properties in the Inspector window to the ones shown in the following screenshot:
Figure 10.22 – Update the Quit Rect Transform property values

Figure 10.22 – Update the Quit Rect Transform property values

  1. The Quit game object will now be in the bottom right of the pause screen:
Figure 10.23 – Our Quit button is added to the pause screen

Figure 10.23 – Our Quit button is added to the pause screen

Next, we can customize it by changing the button's sprite, color, and text. We'll start with the button's sprite by taking off the curved corners that we can see in the previous screenshot.

With our Quit button still selected, we can remove the single sprite by doing the following:

  1. In the Inspector window, click the remote button in the Image component at the top right (denoted as 1 in the following screenshot).
  2. A new window will appear. Select None at the top from the dropdown (denoted as 2 in the following screenshot):
Figure 10.24 – Remove the Source Image sprite for the Quit button

Figure 10.24 – Remove the Source Image sprite for the Quit button

Next, we'll change the color of the buttons, as follows:

  1. With the Quit game object still selected in the Hierarchy window, we can change the Normal Color property on Button Component in the Inspector window.
  2. Select the color field titled Normal Color. Then, in the new pop-up window, change the RGBA settings to red so that it has a slight transparency. The values for it are R: 255, G: 0, B: 0, A: 150.

The next thing we need to do to the button is to change its text.

  1. With our Quit game object still selected in the Hierarchy window, select the drop-down arrow to the left of its name in the Hierarchy window.
  2. Select the Text child game object from the Quit game object and give the Text component in the Inspector window the following property settings:
Figure 10.25 – Update the Text game object's Text Component to the values shown in this screenshot

Figure 10.25 – Update the Text game object's Text Component to the values shown in this screenshot

We will be left with a button that looks more fitting for our game:

Figure 10.26 – Our Quit button now looks more suitable for our game

Figure 10.26 – Our Quit button now looks more suitable for our game

The last thing to do in this section is to duplicate the Quit game object we have just created and rename the text RESUME. The Resume button will be used to cancel the pause screen and let the player continue playing the game.

To create the Resume game object, we will need to do the following:

  1. Select the Quit game object in the Hierarchy window.
  2. Press Ctrl (command on Mac) and D on the keyboard to duplicate the game object.
  3. Rename the duplicated game object from Quit (1) to Resume.
  4. With Resume still selected, change its Rect Transform property values in the Inspector window to the ones shown in the following screenshot:
Figure 10.27 – Give the Resume Rect Transform the same property values as shown in this screenshot

Figure 10.27 – Give the Resume Rect Transform the same property values as shown in this screenshot

All that's left for the Resume game object is to rename its text from QUIT to RESUME by expanding the Resume selection by clicking on its arrow on the left in the Hierarchy window. Follow these steps:

  1. Select the Text game object in the Hierarchy window.
  2. In the Text component in the Inspector window, change the text from QUIT to RESUME, as shown in the following screenshot:
Figure 10.28 – The Resume button

Figure 10.28 – The Resume button

The pause screen is now visually complete and can support various screen ratios thanks to the use of our Anchors from our Rect Transform properties. Earlier, we mentioned that we will have a pause button in the top-left corner of the game screen so that we can pause our game and load up the pause screen that we've just made.

Everything we did in this section was achieved within the Unity Editor without the use of any code. In this section, we covered the following topics:

  • How to access our pause screen
  • How the pause screen would overlay the levels in our game
  • Applying a semi-transparent blackout to dim the game as the pause screen's background
  • Creating sliders for our music and effects
  • Applying custom text to various points
  • Using Unity's Button component to give the player the option to quit or resume the game

Now, let's make the pause button. After that, we can start looking at hooking all these sliders and buttons up with our code.

Adding a game pause button

At the beginning of the previous section, we briefly spoke about the in-game pause button. This button will appear at the start of a level and once pressed, the player, enemies, and bullets that have been fired will freeze in time. In this section, we will only be focusing on the visuals, just as we did with our pause screen in the previous section.

The pause button will act slightly differently from the previous buttons we have made. This time, the button will be an on-or-off-type button. The game object for this will be a toggle as it is more suited to our needs. To make a toggle game object, do the following:

  1. Select the PauseContainer game object in the Hierarchy window, right-click it, and select UI from the drop-down list, followed by Toggle, as shown in the following screenshot:
Figure 10.29 – Add a Toggle (on/off switch)

Figure 10.29 – Add a Toggle (on/off switch)

  1. With the Toggle game object still selected in the Hierarchy window, right-click it, select Rename from the drop-down list, and name it PauseButton.
  2. Currently, our PauseButton looks nothing like how we want it to and resembles a tick box, as shown in the following screenshot. However, we can fix this and make it look like a normal-looking pause button but with the functionality of a toggle (on or off):
Figure 10.30 – We are going to change the tick box to a pause button

Figure 10.30 – We are going to change the tick box to a pause button

To alter the current look of the PauseButton game object so that it looks like the prospective one in the preceding screenshot, we need to do the following:

  1. In the Hierarchy window, click on all of the arrows within the PauseButton game object to expand its content, as shown in the following screenshot:
Figure 10.31 – Expand out all the PauseButton children in the Hierarchy window

Figure 10.31 – Expand out all the PauseButton children in the Hierarchy window

  1. Select the Label game object in the Hierarchy window and press Delete on your keyboard.

The Toggle label will be removed.

  1. Next, we will set our game object to its correct position and scale. Select PauseButton in the Hierarchy window and give its Rect Transform the following properties in the Inspector window:
Figure 10.32 – Update the PauseButton Rect Transform property values

Figure 10.32 – Update the PauseButton Rect Transform property values

The toggle will now be placed and scaled to the top-left corner of the game canvas, as circled in the following screenshot:

Figure 10.33 – The pause button's anchors are set in the top-left corner of the screen

Figure 10.33 – The pause button's anchors are set in the top-left corner of the screen

  1. Notice how our Anchors (the four white arrows) are positioned but the small white tick box's scale hasn't been affected. This means the child of the PauseButton game object that holds another game object titled Background doesn't have its Rect Transform scaled correctly. The following screenshot shows the Background game object selected in the Hierarchy window:
Figure 10.34 – Select the Background game object from the Hierarchy window

Figure 10.34 – Select the Background game object from the Hierarchy window

  1. To correct the Background game object's Rect Transform properties, we need to select the Background game object and give it the following values in the Inspector window:
Figure 10.35 – Set the Background Rect Transform property values to the ones shown in this screenshot

Figure 10.35 – Set the Background Rect Transform property values to the ones shown in this screenshot

The Background game object is now the same size as the PauseButton game object with regard to the Anchor size.

We can now start tweaking the size and filling the Background with a suitable image. We'll replace the white-square-with-a-tick icon with a dark circle. Follow these steps to do so:

  1. With PauseButton still expanded in the Hierarchy window, select the Background game object if you haven't done so already.
  2. Select the small remote button to the right of Source Image in the Image component in the Inspector window.
  3. From the dropdown that appears, replace its current selection with UISprite and change it to Knob. Its selection is shown in the following screenshot.

The square has now become a circle. Now, we can alter its color so that it matches the rest of our game's UI.

  1. With the Background game object still selected, select its Color field and change its RGBA values to R: 92, G: 92, B: 92, and A: 123, as shown in the following screenshot:
Figure 10.36 – Our Background Image Component should have the same values as the ones shown in this screenshot

Figure 10.36 – Our Background Image Component should have the same values as the ones shown in this screenshot

Next, we can make the gray oval shape into a circle.

Still in the Image component, set Image Type to Simple and tick the Preserve Aspect box, as shown in the previous screenshot.

Image Type offers different behaviors to an image; for example, Sliced works well as a progress bar/timer to increment how much of the image can be seen over time.

Preserve Aspect means that no matter which way the image is scaled, it will remain in its original form – there will be no squashed or stretched-looking images.

Here is a close-up view of PauseButton in the Scene view:

Figure 10.37 – What our pause button currently looks like

Figure 10.37 – What our pause button currently looks like

Now, we need to replace the tick image with a large pause symbol. Follow these steps to do so:

  1. Select the Checkmark game object from the Hierarchy window (the child of the Background game object) and in the Inspector window, give its Rect Transform the following settings:
Figure 10.38 – Set the Checkmark Rect Transform property values to the ones shown in this screenshot

Figure 10.38 – Set the Checkmark Rect Transform property values to the ones shown in this screenshot

  1. With the Checkmark game object still selected in Hierarchy, go to the Image component and change Source Image from Checkmark to pause by clicking on the remote button and selecting the pause sprite from the drop-down list.
  2. Select the Color field and give it the following RGBA values: R: 152, G: 177, B: 178, A: 125.
  3. Change Image Type to Simple if it isn't already.
  4. Tick the Preserve Aspect box, as shown in the following screenshot:
Figure 10.39 – Update the Checkmark Image Component property values to the ones shown in this screenshot

Figure 10.39 – Update the Checkmark Image Component property values to the ones shown in this screenshot

The Scene window should look something like this, with our pause button in the top left:

Figure 10.40 – Our pause button is now visually complete

Figure 10.40 – Our pause button is now visually complete

Finally, to make it so that the toggle button actually does something when we click on it, we need to make sure we have an EventSystem in our Hierarchy window. This is very simple to do; follow these steps:

  1. In the Hierarchy window, right-click an open space.
  2. If there isn't an EventSystem in Hierarchy, select UI, followed by EventSystem.
  3. Save the scene.

In this section, we mixed our UI images, buttons, text, and sliders on one screen that supports various landscape variations.

In the next section, we are going to move on to the scripting side of what each of the UI components we made in the pause screen will do when the player presses the buttons or moves the slider.

Creating our PauseComponent script 

The PauseComponent script will have the responsibility of managing anything to do with accessing and altering the conditions the pause screen gives the player. Here, we will follow a series of subsections that will take us through setting up individual segments of the PauseComponent script. Before we do that, though, we need to create our script. If you don't know how to make a script, then revisit the Setting up our camera section in Chapter 2, Adding and Manipulating Objects. Once you've done that, rename the script PauseComponent. For maintenance purposes, store your script in the Assets/Script folder in the Project window.

Now, let's move on to the first subsection of the PauseComponent script by applying logic to the in-game pause button.

PauseScreen basic setup and PauseButton functionality 

In this section, we are going to make the pause button appear when the player has control of the game in the level. When the player presses the pause button, we need to make sure that all the moving components and scrolling textures freeze. Finally, we need to introduce the pause screen itself.

If we start the level in its current state, we will see that the PauseScreen game object overlays the screen. This looks great, but we need to turn it off for the time being. To turn off the PauseScreen game object, do the following:

  1. In the Unity Editor, open the newly created PauseComponent script by double-clicking the file held in Assets/Script.
  2. With the script open, add the UnityEngine UI library at the top to give us extra functionality for our code (manipulate text and image components), including the usual UnityEngine library and the name of the class, along with its inheritance of MonoBehaviour:

    using UnityEngine.UI;

    using UnityEngine;

    public class PauseComponent : MonoBehaviour

    {

  3. Add the following variable to the PauseComponent class:

    [SerializeField]

              GameObject pauseScreen;

    }

[SerializeField] will keep the pauseScreen variable exposed in the Inspector window as if it were public. The second line is a GameObject type that will store a reference to the entire PauseScreen game object.

  1. Save the script.
  2. Back in the Unity Editor, select the PauseContainer game object from the Hierarchy window. In the Inspector window, click Add Component and type PauseComponent until you see it in the drop-down list.
  3. Now, drag and drop the PauseScreen game object from the Hierarchy window into the empty game object slot titled PauseScreen, as shown in the following screenshot:
Figure 10.41 – Drag and drop the PauseScreen game object into the Pause Component | Pause Screen field

Figure 10.41 – Drag and drop the PauseScreen game object into the Pause Component | Pause Screen field

Back in the PauseComponent script, we can now turn off the PauseScreen game object at the beginning of the level and turn it back on when the player presses the pause button. To turn PauseScreen off, we can do the following:

  1. In the PauseComponent script, create an Awake function and inside it, turn the pauseScreen game object off, as shown in the following code:

      void Awake()

      {

        pauseScreen.SetActive(false);

      }

  2. Save the script.

We can now test it in the Editor when we press the Play button at the top of the screen. The game will run without the pause screen being shown. Now, we can focus on introducing the pause button to the player within a few seconds as the level begins.

Let's start by creating a method that will turn off/on the visuals and the interactability of the pause button for the player:

  1. Go back into the PauseComponent script and create a method that takes one bool parameter, as shown in the following code:

      void SetPauseButtonActive(bool switchButton)

      {

With our PauseComponent script being attached to the PauseContainer game object, we can easily access any of the game objects and their components. The other two main game objects attached are PauseScreen and PauseButton. The next few pieces of code we will add to our SetPauseButtonActive will relate to the visuals and interactivity of the PauseButton game object.

  1. To change the visibility of our PauseButton, we need to access its Toggle component's colors value and store it in a temporary ColorBlock type. Enter this line of code inside the SetPauseButtonActive method:

    ColorBlock col = GetComponentInChildren<Toggle>().colors;

  2. Next, we need to check the condition of the value by looking at the bool parameter the method is receiving. If the switchButton bool is set to off, then we are going to set all colors related to the toggle to zero, which is black and zero alpha (completely transparent).

Enter the following code just after the line of code we entered previously:

    if (switchButton == false)

    {

      col.normalColor = new Color32(0,0,0,0);

      col.highlightedColor = new Color32(0,0,0,0);

      col.pressedColor = new Color32(0,0,0,0);

      col.disabledColor = new Color32(0,0,0,0);

      GetComponentInChildren<Toggle>().interactable =     false;

    }

The preceding code shows that we run a check to see whether the bool parameter is false.

  1. If switchButton does contain a false value, then we step into the if statement and set the col (the color of the pause button) normalColor property to all zero. This means that it doesn't display this button at all. Then, we apply the same value to all of the other possible color states for the pause button. We also need to set the Toggle interactable value to false so that the player can't accidentally press the pause button either.

The screenshot on the left in the following figure shows the code we've just entered. The screenshot on the right is the Toggle component with the properties we have changed in our if statement:

Figure 10.42 – The code on the left will manipulate the Toggle property values on the right

Figure 10.42 – The code on the left will manipulate the Toggle property values on the right

If switchButton is set to true, we set the values from all zeros to their chosen color values and make the PauseButton intractable.

  1. Enter the following code just after the preceding code that we just wrote:

        else

        {

          col.normalColor = new Color32(245,245,245,255);

          col.highlightedColor = new Color32(245,245,245,255);

          col.pressedColor = new Color32(200,200,200,255);

          col.disabledColor = new Color32(200,200,200,128);

          GetComponentInChildren<Toggle>().interactable = true;

        }

The last two lines after this piece of code are applying the col value back to the Toggle component.

The second line of code turns the pause symbol on or off. If this wasn't set, then the pause button would appear/disappear without affecting the two white pause stripes.

  1. The last two GetComponentInChildren lines are added after the preceding code, which reapplies the color back to the Toggle component and the pause symbol to on or off with the use of the switchButton variable:

    GetComponentInChildren<Toggle>().colors = col;

    GetComponentInChildren<Toggle>()

      .transform.GetChild(0).GetChild(0).gameObject.SetActive

         (switchButton);

    }

  2. Now, all we need to do is make use of the method we've just written. Originally, we wanted the pause button to not be in view at the start of the level until the player has control of their ship. To turn off the pause button, we need to revisit the Awake function and do the following:

      void Awake()

      {

        pauseScreen.SetActive(false);

        SetPauseButtonActive(false);

        Invoke("DelayPauseAppear",5);

      }

Here, I have added two extra lines of code in the Awake function. SetPauseButtonActive(false) turns the pause button off with the method we've just made, while the Invoke function will delay for 5 seconds until we run the DelayPauseAppear method. Inside DelayPauseAppear is SetPauseButtonActive(true), which is the time when our player gains control of their ship.

  1. Add the extra method that we mentioned in the Invoke function to turn the pause button on, as follows:

      void DelayPauseAppear()

      {

        SetPauseButtonActive(true);

      }

  2. Save the script.

Back in the Unity Editor, press Play; our game will start normally and after 5 seconds, the pause button will appear in the top-left corner. If we press the pause button, it will break and nothing extra will happen. This is because we haven't made the pause button do anything when it is pressed.

Let's return to the PauseComponent script and add a small method that can run when the pause button is pressed. To add a pause method that freezes the game and brings up the pause screen we built earlier, follow these steps:

  1. Reopen the PauseComponent script and enter the following method:

      public void PauseGame()

      {

        pauseScreen.SetActive(true);

        SetPauseButtonActive(false);

        Time.timeScale = 0;

      }

  2. Within the PauseGame method, we set the following:
    • We set the pause screen game object's activity to true.
    • Turn off the pause button (because we have the QUIT button to use instead).
  3. Set the game's timeScale to 0, which will stop all moving, animating objects in the scene. For more information about timeScale, check out the official Unity documentation here: https://docs.unity3d.com/ScriptReference/Time-timeScale.html.

timeScale can also be found in Time Manager in the Unity Editor. This is located at the top of the Editor window, under Edit | Project Settings | Time.

You also have other useful properties such as Fixed Timestep, where you can change its value to make your physics simulation more precise. For more information about Time Manager and its properties, check out the following link: https://docs.unity3d.com/Manual/class-TimeManager.html.

  1. Save the script and return to the Editor.

Now, we need to attach the new PauseGame method to the PauseButton event system, as follows:

  1. Select the PauseButton game object from the Hierarchy window.
  2. At the bottom of the Inspector window, click the plus (+) sign to add an event:
Figure 10.43 – Add an Event to the Toggle Component

Figure 10.43 – Add an Event to the Toggle Component

  1. Next, drag PauseContainer, which contains our PauseComponent script, to the empty field (denoted as 1 in the following screenshot). Then, click the No Function field and select PauseComponent from the dropdown (denoted as 2 in the following screenshot).
  2. Lastly, select the PauseGame () public method (denoted as 3 in the following screenshot).

The following screenshot shows the marked-out steps we have gone through in selecting the PauseGame () method:

Figure 10.44 – Drag PauseContainer from the Hierarchy window into the Event slot; finally set its function to PauseGame ()

Figure 10.44 – Drag PauseContainer from the Hierarchy window into the Event slot; finally set its function to PauseGame ()

Now would be a good time to try and see whether the pause screen appears when we press the pause button. Press Play in the Unity Editor and in the Game window, press the pause button in the top-left corner when it appears. The pause screen will appear; we won't be able to escape from this until we code in the logic for our Resume and Quit buttons.

So far in this section, we have given the player the ability to pause the game. In the next section, we will make it so that the player will be able to resume or quit the game from the pause screen.

Resuming or quitting the game from the pause screen

In this subsection, we will continue to extend the PauseComponent script by adding two methods:

  • Resume
  • Quit

Let's make a start by adding the logic for the Resume button; follow these instructions:

  1. If the PauseComponent script isn't open already, go to the Project window and locate the file at Assets/Script. Double-click the file to open it.
  2. Inside the PauseComponent script, scroll to a point where we can add a new method – it doesn't matter where, as long as it's inside the PauseComponent class and not interfering with other methods.
  3. Now, we are going to add a Resume method where if the player wishes to close the pause screen, the game animation continues, and the pause button in the top-left corner reappears. To make all of this happen, add the following code:

      public void Resume()

      {

        pauseScreen.SetActive(false);

        SetPauseButtonActive(true);

        Time.timeScale = 1;

      }

This code is similar to the code shown in the previous section; it's just in the opposite order (instead of the value being set to true, it's now false and vice versa to bring back the original settings).

  1. Save the script and return to the Unity Editor.
  2. In the Unity Editor, select the RESUME button from the active PauseScreen game object. Make sure the Hierarchy window also shows that Resume is selected.
  3. At the bottom of the Inspector window, click and drag the PauseContainer game object from the Hierarchy window into the None (Object) On Click () event system.
  4. Select the No Function field and select PauseComponent, followed by Resume (). The following screenshot shows the On Click () event system set up correctly for the Resume game object button:
Figure 10.45 – The Resume button's On Click () event hooked up to the Resume function

Figure 10.45 – The Resume button's On Click () event hooked up to the Resume function

  1. Let's test the Resume button before moving on to the Quit button. Press Play in the Editor. Once the pause button appears in the top left of the Game window, click it.
  2. Finally, click the big Resume button. We will be brought back to the game playing out.
  3. The last button to hook up in our pause screen is the Quit button. Reopen the PauseComponent script and add the following method to the script:

      public void Quit()

      {

        Time.timeScale = 1;

        GameManager.Instance.GetComponent<ScoreManager>().    ResetScore();

        GameManager.Instance.GetComponent<ScenesManager>().    BeginGame(0);

      }

The code we've just entered resets the game; the timescale value goes back to 1. We reset the player's score from ScoreManager directly and also directly told ScenesManager to take us back to scene zero, which is our bootUp scene.

  1. Save the script before ending this section.

This is similar to the Resume button in regard to setting up an event to our script.

  1. Select the QUIT button from the pause screen and make sure that, at the bottom of the Inspector window, you follow the same steps that you followed for the Resume button.
  2. When we get to applying the QUIT button's function, change the field from No Function to the Quit method.

The following screenshot shows the Quit game object's button setup:

Figure 10.46 – When the Quit button is pressed, it will run the Quit function

Figure 10.46 – When the Quit button is pressed, it will run the Quit function

Before we wrap up this chapter, we need to ensure that the player and enemies behave how we expect them to when the game is paused.

Pausing the player and enemies

So, we have reached the point where we can press our in-game pause button and watch our game freeze in time. To make sure the scene is saved, including new and edited scripts, let's test the pause screen:

  1. Press Play in the Unity Editor.
  2. When the pause button appears, press it.
  3. The game pauses, but our enemies appear to float off. Also, when we press the fire button for the player, its player bullet light glows on the ship.

Let's fix the enemy floating first.

  1. This is an easy fix – we need to change the update time for our EnemyWave script.
  2. Stop playing. Then, in the Project window, navigate to Assets/Script and double-click the EnemyWave script.
  3. Find the line that states the following:

    void Update()

Change this to the following:

void FixedUpdate()

  1. Save the EnemyWave script.

    Further Information

    More information about FixedUpdate can be found here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html.

Now, let's reinforce the player's behavior so that all of its functionality is frozen when the game pauses. To freeze our player, we need to reopen its script:

  1. In the Project settings window, navigate to the Assets/Script folder.
  2. Double-click the Player script.
  3. Scroll down to the Update function and wrap the player's Movement and Attack methods with the following if statement:

       void Update ()

      {

        if(Time.timeScale == 1)

        {

          Movement();

          Attack();

        }

      }

The preceding code runs a check to see whether the game's timeScale is running at full speed (1) and then carries on with the Movement and Attack methods.

  1. Save the Player script.

Great! We now have the ability to pause our game, continue our game, or quit it. Don't worry about adding this pause screen to the rest of the levels as we will do this in the next chapter. Speaking of the next chapter, there, we will look at how we can change the Music and Effects sliders. For now, let's reflect on what we have covered in this chapter.

Summary

By completing this chapter, our game has improved even more and now has a pause screen, just as you would expect from any game. We also learned how to freeze time in our game with the timeScale value. We did revisit some things we covered in previous chapters such as Event Listeners and UI positioning and scaling, but we also used other UI components such as toggles and sliders and modified them to suit our pause screen. Other things we covered included bringing in some MP3 music and making it so that the script knew when to fade in and out and stop the soound.

In the next game you create outside of this book, you will know not only how and when to add background music to play when it's playing but also how to attach your audio to a state machine. With state machines, you can make it possible for your music to be played, stopped, and faded out when particular moments occur, such as the game's screen being paused. Now, you will be able to take the UI components you've learned about in this chapter and create your own menu/pause screen. By doing this, you can run events to close or resume your game. You also know how to pause your game completely and/or slow time down with the timeScale function.

In the next chapter, we will be looking at Unity's Audio Mixer to control the volume of our player's bullets and music and hook it up to our pause screen volume sliders. We will also look into different types of data that need to be stored, such as our game remembering the volume settings so that we don't have to adjust the sliders every time we start our game.

For now, I wish you the best of luck with your mini mock test!

Mock test

  1. If you want to keep a private variable visible in the Inspector window, which attributes should you put above the variable in your code?
    1. [Header]
    2. [SerializeField]
    3. [AddComponentMenu]
    4. [Tooltip]
  2. You have created a pinball game for a mobile device; the game mechanics all work well but you also need to apply a pause screen. Obviously, when the player presses pause, the entire game should freeze. The way you are going to achieve this is by setting Unity's timeScale to zero.

Which time property isn't affected when we set Time.timeScale to 0?

  1. captureFramerate
  2. frameCount
  3. realtimeSinceStartup
  4. timeSinceLevelLoad
  1. There is a list of scenes in your BuildSettings window. You know that the first scene is your title scene and that the rest that follow are your game's level scenes. Your game designer hasn't settled on the names of the scenes and keeps changing them. As a programmer, you can select the scenes to load by using what SceneManager method?
    1. GetSceneByBuildIndex()
    2. GetActiveScene()
    3. SceneManager.GetSceneByName()
    4. SceneManager.GetSceneByPath()
  2. If you have a pause screen that can be enabled or disabled, which is the best UI component to switch between the two?
    1. Toggle
    2. Button
    3. Slider
    4. Scroll Rect
  3. A new prototype of Killer Wave is handed to you on a mobile device for testing. You notice you can move the ship or shoot when you enter a level with UI text in the middle of the screen. What would be causing the restriction in movement?
    1. The ratio of the screen's proportion is out of calibration.
    2. The UI text has Raycast Target ticked.
    3. The mobile device needs charging.
    4. Too many fingers on the screen at once has confused the Input system.
  4. You have created a UI button that displays an image of coins on it when you have money in your account and an image of an empty brown bag when your account is empty.

What should the Transition field of the button be set to in the Unity Inspector to support these image changes?

  1. Color Tint
  2. None
  3. Animation
  4. Sprite Swap
  1. While entering some UI details at the bottom of the screen to show your player's lives and what level they are on, you notice you need the text to be a specific size. You can change the text to any size you want, but you also need to accommodate the ratio of the screen.

What's the best way of amending the font to make sure it doesn't appear squashed?

  1. Decrease Font Size.
  2. Turn on Best Fit.
  3. Set Vertical Overflow to Truncate.
  4. Set Horizontal Overflow to Overflow.
  1. You have started working on a game that relies on time being stopped, rewound, and fast forward, but only for your enemies, with the use of the Time.timeScale functionality. Some of your enemies aren't being affected by the change of time.

What property value could potentially cause this in the enemy's Animator component?

  1. Set Update Mode to Animate Physics.
  2. Set Culling Mode to Cull Completely.
  3. Set Culling Mode to Always Animate.
  4. Set Update Mode to Unscaled Time.
  1. You have a selection of game objects that are tomato plants. Each tomato on the tomato plant has a script attached named Tomato.

In order to avoid the tomato plants appearing repetitively, some of the artists have turned off the tomato game objects so they can't be seen.

At the start of the scene, we need to count how many tomatoes are in the scene, including the hidden ones.

Which command would get a reference to all Tomato scripts?

  1. GetComponentsInChildren(typeof(Tomato), true)
  2. GetComponentInChildren(typeof(Tomato), true)
  3. GetComponentsInChildren(typeof(Tomato))
  4. GetComponenstInParent(typeof(Tomato), true)
  1. Which static Time class property would be used to freeze time?
    1. timeScale
    2. maximumDeltaTime
    3. captureFramerate
    4. time
  2. Which of the following would be the most useful for labeling in a state machine?
    1. Enum
    2. String
    3. Float
    4. Int
  3. Which of the following is related to triggering an event in-game?
    1. A particle effect is running.
    2. The player is idle on the menu screen for 20 minutes.
    3. The player presses a UI button.
    4. The player moves the mouse cursor.
  4. You have created a game where your player must sneak around and avoid the enemy. In one of the missions, your player has to listen out in the warehouse where the enemy is (listening for footsteps, talking, and so on).

What audio property would you add for this game?

  1. Add an Audio Source component to each enemy, set its spatial blend to 3D, and play a sound.
  2. Use an Audio Mixer Snapshot to add a low-pass filter when enemies are nearby.
  3. Measure the distance between each enemy and the player and play a sound if the distance drops below a certain threshold.
  4. Add an Audio Source that plays music in the background and increase or decrease its volume based on the distance of the closest enemy.
  1. Within your Audio Source component, which property will make the sound go from 3D to 2D?
    1. CustomRolloff
    2. SpatialBlend
    3. ReverbZoneMix
    4. Spread
  2. You have started adding music and sound effects to your game. When testing, you notice that the background music cuts out when some sound effects are played.

Which property in the Audio Source component will fix this so that your music doesn't cut out?

  1. Increase Priority.
  2. Increase Volume.
  3. Increase MinDistance.
  4. Decrease SpatialBlend.
  1. You have been asked to make a UI menu screen. You have made a Canvas and set its Render Mode to Screen Space - Overlay.

In the Canvas Scaler component, which property in UI Scale Mode will make UI elements retain the same size in pixels, regardless of screen size?

  1. Constant Pixel Size
  2. Scale with Screen Size
  3. Constant Physical Size
  4. Disable Canvas Scaler
  1. When ticking the Preserve Aspect checkbox in an Image component, what does this do?
    1. Sets the aspect of the camera to match the perspective of the image.
    2. Makes the image match the same aspect ratio as the cameras.
    3. The image retains its original dimension.
    4. Has no effect on Image components, only Sprite Renderers.
  2. Can a Sprite Renderer be used instead of an Image component within the Canvas?
    1. No. Even though a Sprite Renderer can work in 2D/3D spaces, it's not intended to be used with the Canvas and therefore will not work.
    2. Yes, but Sprite Renderer has fewer features and is an older version of the Image component.
    3. Depending on the Unity project, if your scene is in 2D mode, yes.
    4. Yes, when being used to animate sprite sheets.
  3. What does the Graphic property do in the Toggle component by default?
    1. Holds the graphic for the Toggle component
    2. Turns the Toggle button on or off
    3. Makes the graphic active or inactive when the player presses it during runtime
    4. Holds the CheckMark image
  4. What does Interactable do when disabled on the Toggle component?
    1. Hides the game object.
    2. It changes the color of the Toggle and has no effect when pressed.
    3. Disables the Toggle from working at runtime.
    4. Destroys the Toggle's parent game object.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset