Sound volume adjustment can be a very important feature, especially if your game is a standalone. After all, it can be very frustrating needing to access the operational system volume control. In this recipe, we will create a sound volume control GUI that can be switched from a single volume bar to independent music and effects controls.
For this recipe, you'll need the soundFX.wav
and soundtrack.mp3
audio files, available in the 0423_06_02
folder.
To add volume control sliders to your scene, follow these steps:
soundtrack.mp3
audio file.soundtrack.mp3
file. Make sure the 3D Sound option of the Audio Importer (in the Inspector view) is unselected. If not, unselect it.soundFX.wav
audio clip. This time, we will make sure to leave the 3D Sound option checked.FXSource
. Set its position to X:0, Y:0, Z:6.VolumeControl
.using UnityEngine; [RequireComponent(typeof(AudioSource))] public class VolumeControl : MonoBehaviour{ bool separateSoundtrack = true; float minVolume = 0.0f; float maxVolume = 1.0f; float initialVolume = 1.0f; float soundtrackVolume = 1.0f; bool displaySliders = false; void Start(){ if (separateSoundtrack){ audio.ignoreListenerVolume = true; } } void Update(){ AudioListener.volume = initialVolume; if (separateSoundtrack){ audio.volume = soundtrackVolume; }else{ audio.volume = initialVolume; } } void OnGUI(){ Event e = Event.current; if (e.type == EventType.KeyUp && e.keyCode == KeyCode.Escape){ displaySliders = !displaySliders; } if (displaySliders){ if (!separateSoundtrack){ GUI.Label(new Rect(10, 0, 100, 30), "Volume"); initialVolume = GUI.HorizontalSlider(new Rect(10, 20, 100, 30), initialVolume, minVolume, maxVolume); }else{ GUI.Label(new Rect(10, 0, 100, 30), "Sound FX"); initialVolume = GUI.HorizontalSlider(new Rect(10, 20, 100, 30), initialVolume, minVolume, maxVolume); GUI.Label(new Rect(10, 40, 100, 30), "Music"); soundtrackVolume = GUI.HorizontalSlider(new Rect(10, 60, 100, 30), soundtrackVolume, minVolume, maxVolume); } } } }
By default, every sound in the scene has its volume controlled by the Volume parameter of the camera's Audio Listener component. With our script, we assign the Volume slidebar value to that parameter. Also, we create a separate volume bar for the soundtrack.mp3
file, making it independent from the camera's Audio Listener component.
Here is some information on how to fine-tune and customize this recipe.
If you need to simplify the volume controls even more, you can use a single volume bar by leaving the Separate Soundtrack option unchecked.
18.225.57.126