Now that we have a volume slider, let's add an enable/disable sound checkbox, which will turn down the volume to 0 and hide our volume slider.
First, create a toggle widget as follows:
Sound
. It will be our sound toggle container.A checkbox with a label has just been created as shown in the following screenshot:
Select our new Toggle GameObject. Let's look at the UIToggle's Inspector parameters:
We have seen the UIToggle's parameters. Now we will create this sound toggle as shown in the following screenshot:
Let's use our recently added Toggle GameObject to create the window shown here. Follow these steps to do so:
-420
, 43
}.[AAFFFF]Sound
.-38
, -20
}.3
.130
, G to 255
, B to 130
, and A to 255
.4
.50
, G to 255
, B to 70
, and A to 255
.3
.[AAFFFF]Enabled
.200
, G to 255
, B to 250
, and A to 255
.Hit the Play button. We have a nice sound box with a sound toggle checkbox that hides/shows the Volume box when needed. But it does not turn off the sound yet.
We need to make some changes to our VolumeManager.cs
script to correct this.
First, open our VolumeManager.cs
script. We will add a new OnSoundToggle()
method that will be called when the toggle changes state. It will set the volume directly to 0, or to the slider's value. Add this new method to VolumeManager.cs
as shown in the following code lines:
public void OnSoundToggle() { float newVolume = 0; //If sound toggled ON, set new volume to slider value if(UIToggle.current.value) newVolume = slider.value; //Apply newVolume to volumes AudioListener.volume = newVolume; NGUITools.soundVolume = newVolume; }
Ok, the previous method will set both our volumes to 0
or the slider's value, depending on the toggle's state. Let's link it to our sound's toggle by selecting our Toggle GameObject and dragging the Slider GameObject from Volume inside the Notify field in UIToggle, below the On Value Change section. Then, for the Method field, select VolumeManager.OnSoundToggle
.
Hit the Play button. That's it. When we click on the Toggle checkbox from Volume, the volume reacts accordingly.
But if we turn the sound off using the toggle and stop running, when we hit Play again, the checkbox is still checked and the volume slider is displayed, but the volume is at 0
.
That's because our volume is set to 0, but the checkbox is still checked at start. Let's add a simple line of code that will set the start state to false
if the volume is at 0
:
VolumeManager.cs
script.public UIToggle soundToggle
.Awake()
method, add the following lines of code://If volume is at 0, uncheck the Sound Checkbox if(NGUITools.soundVolume == 0) soundToggle.value = false;
Drag theToggle GameObject from Volume in the volume manager's Sound Toggle field.
Hit the Play button. That's it. If you disable sound using the toggle and exit the Play mode and then launch it again, the checkbox stays unchecked and the volume slider is not displayed. Perfect!
3.21.12.140