Now let's add a volume slider for the user to move and select his/her volume level.
A slider template is available, enabling you to adjust parameters easily by sliding a thumb along a bar. Perform the following steps to create a volume slider:
Volume
. It will be our volume settings container.A slider has been created. It has 6 parameters as follows:
We can use this slider to create our volume slider, which will look like the following screenshot:
Proceed with the following steps to create it:
320
x 135
.-420
, -90
}.[AAFFFF]Volume
.-100
, -23
}.3
.80
, G to 220
, B to 85
, and A to 255
.4
.95
, G to 255
, B to 190
, and A to 255
.5
.100
, G to 255
, B to 250
, and A to 255
.Ok, we now have a nice volume slider! Your Hierarchy view should look like the following screenshot:
We will now link it to the game's volume with a new script. Let's add some music to our main menu. First, add an audio file of your choice to your Unity project as shown in the following steps:
VolumeManager.cs
C# script to it.VolumeManager.cs
script.In this new script, we will first need to declare and initialize the necessary variables. Add the following variable declarations and the Awake()
method:
//We will need the Slider
UISlider slider;
void Awake ()
{
//Get the Slider
slider = GetComponent<UISlider>();
//Set the Slider's value to last saved volume
slider.value = NGUITools.soundVolume;
}
Here we initialized the slider's value to NGUITools.soundVolume
because this float is persistent and will be saved across scenes—even if you exit the game.
Now let's create an OnVolumeChange()
method that will modify our AudioListener method's volume each time the slider's value is changed:
public void OnVolumeChange () { //Change NGUI's UI Sounds volume NGUITools.soundVolume = UISlider.current.value; //Change the Game AudioListener's volume AudioListener.volume = UISlider.current.value; }
Ok, the method is ready. We just need to call it each time the slider's value changes. Let's use the UISlider component's Notify field as follows:
VolumeManager.OnVolumeChange
.Now, each time the slider's value is modified, our method will be called.
You can hit the Play button; the game's volume will change with the slider. The volume is saved even when you exit the game and restart!
3.139.97.53