Audio sliders in Unity
Objective: Creating an audio slider that adjusts game sound volumes and saves them for when the player returns to the game.
Making an adjustable sound slider is a quick way to give your player some control over the game.
First, you will need to create a slider in the Canvas. I will be using two sliders for my game, one for the background music and one for all the sound effects.
I have already created a singleton called GameData and this contains all of the game audio for my game. Please see my previous article about sound.
I am using two scripts, one for updating the sound and one for the music. Once the sliders have been made, I then attach the scripts to the relevant sliders.
Let us start with the background music slider.
First I am creating a list of AudioSources. Once the game has started I am populating the list with the first audio source in the array, which is where my background music is stored in the GameData object.
I am then grabbing the Slider component, then storing the slider value inside the PlayerPrefs. If there is already a key for the musicVolume then I am setting the volume to that value, else I am setting the value with a hard value.
I am then using my UpdateMusicVolume method to update the player prefs and setting the volume of each audiosource in the List. This is also happening in the sound script, this means that all the sound effects will have the same volume.
The sound effects script is very similar but more items are added to the initial list in the sound start method.
For this, I am starting the for loop at position 1 of the array. This will skip the background music and start at the first sound effect. Everything else is the same as the music script.
Now I need to make sure that the GameData script knows about the sliders when it starts.
I then set these up in the Unity editor and now I need to hook up the methods on the sliders so that when the slider is adjusted it will automatically update the playerprefs with the new value.
You will see in Unity on the Slider that there is an option for on value changed. You need to drag in the slider component here and then you will have access to the update method, the one you will need to choose is the dynamic float option at the top and not the same method at the bottom as the bottom option requires a hard value inserted.
That is it for this article on creating sound sliders in Unity.