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.
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.
public AudioClip bkgdClip; static private float volumeLevel;
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); }
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; }
bkgd_01
from the Project panel into the Audio Clip slot of the script, as shown in the following screenshot: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.
18.225.254.192