Game options – volume level

Among the extra features we are adding to the prototype, we'd like to provide an example of options screen functionality by showing you how to set up a horizontal slider to control the volume of the background music carpet.

Getting ready

For this recipe, we will use the bkgd_01 audio clip we imported at the beginning of this chapter. Open your project in Unity and ensure that bkgd_01 is configured in the Inspector window, as we did in the first recipe of this chapter.

How to do it...

  1. To make Option Screen for the prototype, we begin by creating a new scene and naming it Option Screen.
  2. Next, add an empty game object to the scene and name it GUI.
  3. Add an Audio Source component to the GUI game object in the scene. Remember that whenever you want a game object to play a sound, an Audio Source component must be attached to it.
  4. Now we add a script to the game object, with the instructions to draw the interface and control its functionality. Create a new C# script and name it VolumeController.
  5. Double-click on the script to open it in Monodevelop.
  6. First of all, we need two public variables, one to store the reference to the audio clip we want to be played, and the other to store the actual volume level based on the position of the horizontal slider. We make this second variable static so that we can access its value anywhere. Add the following lines to the script:
    public AudioClip bkgdClip;
    static private float volumeLevel;
  7. Now we need the OnGUI() function to draw the slider on screen and set the volume level. Add these lines to the script:
    void OnGUI(){
        volumeLevel = GUI.HorizontalSlider( new Rect(30,30,110, 30), volumeLevel, 0.0f, 			10.0f);
    }
  8. To end with scripting, we need to add a line to the Update() function to check whether the volume at which the sound is played is the same as the volume that is set on the slider. This is done with the following instruction in the Update() function:
    void Update () {
    
        audio.volume = volumeLevel;
        
    }
  9. The final step is to drag the audio clip asset named bkgd_01 from the Project panel into the Audio Clip slot of the script, as shown in the following screenshot:
    How to do it...

How it works...

The horizontal slider works as expected. By moving the cursor left or right you adjust the volume the background music is played at, in a range that goes from volume = 0 to volume = 10.

Let's improve the Options Screen functionality by allowing the user to toggle the audio clip on or off with the next recipe.

..................Content has been hidden....................

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