The right way to make a volume slider in Unity (using logarithmic conversion)

JohnUnity

Creating a UI slider volume control in Unity is straightforward, by using exposed parameters, the Audio Mixer and a simple script. This is useful for creating UI audio volume controls for your player.

There’s just one problem…

…Unity’s standard tutorial, although good, misses out on a crucial step that makes the slider control much too sensitive and difficult to use.

This happens because the slider value is linear but the audio mixer value (the attenuation) is logarithmic.

Luckily, however, there’s a very simple fix. In this post I’ll show you how to prevent the sensitive slider issue and make a, smooth, audio control slider:

If you haven’t already seen it, you can check out Unity’s official tutorial here, or my own tutorial video below but, if not, don’t worry, because you’ll also find step by step instructions later on in this post that include a fix for the sensitive slider issue.

The Sensitive Slider Issue: Why is this a problem?

If you create an audio slider using the standard method, and reduce the slider to about halfway, you’ll find that the audio isn’t half as loud (as you might expect), in fact it’s virtually silent.

This is because the volume range of the Audio Group fader, which is in decibels, is logarithmic meaning that the increments are exponential. Each increment on the scale represents a greater and greater value: e.g. 10, 100, 1000 and so on. In comparison the slider scale is linear and the increments are evenly spaced: e.g. 1, 2, 3.

Normally we perceive half volume to be at around -6db. However, moving the slider to halfway doesn’t do this. In fact, at halfway, it actually sets a value of -40db which is almost at the bottom.

To fix this, the linear slider value needs to be converted.

The difference this makes is clear when comparing the two methods side by side:

Unity Volume Slider Example

On the far right is the fader response using the standard ‘direct’ method. To the left of this is a fader using the ‘converted’ method

The quick & easy fix to prevent the sensitive slider issue

If you already have this issue, and you just want to fix it, here’s what to do:

  • Use a slider value range of 0.0001 – 1
    instead of -80db – 0db (the 0.0001 is important, and stops the slider breaking at zero)
  • When passing the slider value to the SetFloat function, convert it using Mathf.Log10(value) * 20;
    e.g. mixer.SetFloat(“MusicVol”, Mathf.Log10(sliderValue) * 20);

For full instructions, including this fix, keep reading, and follow the steps below.

How to create a UI volume control slider in Unity (that actually works)

Create the slider

  1. In the hierarchy select Create > UI > Slider to create a UI Slider for your volume control
  2. Select the Slider object and set the Min Value to 0.0001 (the logarithmic conversion will not work correctly at zero)
  3. Set the Value to 1
    Unity Volume Slider Inspector Settings

Expose the Audio Mixer Group volume to scripting

  1. Select the Audio Mixer Group that you want to control with the slider
  2. In the inspector, under attenuation, right click on the volume label and select Expose ‘Volume (of Music)’ to script
    Expose Parameter in Unity
  3. In the Audio Mixer Panel, select the Exposed Parameters dropdown and give the, now exposed, volume parameter a name. e.g. “MusicVol”. You’ll need to use the parameter name given here when accessing it from a script.
    Exposed Parameters Menu

Connect the slider with a script

  1. Add a new C Sharp script to the slider object called SetVolume or similar.
  2. Open it for editing and type, or paste, the following script:
  3. Save the script and return to Unity.
  4. Use circle select to connect the mixer reference variable to the Mixer that contains the exposed parameter.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class SetVolume : MonoBehaviour {
    public AudioMixer mixer;
    public void SetLevel (float sliderValue)
    {
        mixer.SetFloat("MusicVol", Mathf.Log10(sliderValue) * 20);
    }
}

Important: If you’re just copying the function, not the whole script, remember to add the using UnityEngine.Audio namespace at the top of the script. This is required to access Audio Mixer functions.

Add the function to the slider

  1. Select the slider object and add a new ‘On value changed’ event.
  2. Drag the SetVolume script to the field or set it by using circle select.
  3. Select the function dropdown, where it currently reads ‘no function’. Select the SetVolume script and then select the SetLevel function (listed under Dynamic float*).
    Connect slider to volume control function in Unity

* If the function doesn’t appear under the dynamic float list make sure that 1. the access modifier for the function is set to public and 2. that the function takes a single float parameter.

Important: The Dynamic Float option is missing in Unity 2019.2.5 due to a suspected bug. Use the workaround at the end of this article to fix it.

Save the scene and hit play to test

The slider should now control the Audio Mixer Group fader.

Repeat to create music and audio volume controls. You can even use multiple mixer groups to give players more granular control over voices, sound effects, music and other sound categories.

Extending the script: How to save and load the volume slider value

Now that you’ve created a volume control, you may wish to save the value whenever it’s changed so that the volume level, and the slider position, stay the same if you load a different scene or restart the game.

Thankfully, this is easy to do by using the PlayerPrefs class, which allows you to store and reload player preferences between games. By adding just a few new lines to the same script we will be able to:

  • Save the slider value whenever it’s changed (this sets the Player Preference, using a string value to identify it).
  • Recall the saved slider value whenever the script is loaded or, if there isn’t a saved value, load a default value instead.

Here’s how to use PlayerPrefs to save the volume slider value:

  1. Add the using UnityEngine.UI; namespace to the script.
  2. Declare a public Slider variable, call it slider or similar then connect it in the inspector
  3. In the SetLevel function, add a new line: PlayerPrefs.SetFloat(“MusicVolume”,sliderValue);
    This will save the value of the slider whenever it’s changed.
  4. In the Start function (please note that this will not work in Awake, add a new line: slider.value = PlayerPrefs.GetFloat(“MusicVolume”, 0.75f);
    It’s important to include the default value parameter (in my case I’ve used 0.75f). Otherwise the default for the variable type will be used which, for a float, is 0.

Here’s what the new script looks like:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class SetVolume : MonoBehaviour {
    public AudioMixer mixer;
    public Slider slider;
    void Start()
    {
        slider.value = PlayerPrefs.GetFloat("MusicVolume", 0.75f);
    }
    public void SetLevel (float sliderValue)
    {
	mixer.SetFloat("MusicVol", Mathf.Log10(sliderValue) * 20);
        PlayerPrefs.SetFloat("MusicVolume", sliderValue);
    }
}

Note that changing the slider value in Start also triggers the SetLevel function, so it updates the mixer to the correct loaded value too.

Why does the saved volume only load when I open the settings menu

In this example, the SetVolume script has been added to the Slider object itself.

In an isolated example this is fine, however, if, like many people, you show and hide the menu settings panel by disabling its parent object, then this will mean that the Slider script will not load when the Scene is first loaded and will instead only load once the player navigates to the menu panel.

The easiest way to fix this is by moving the SetVolume Script to an object that will not be disabled at the beginning of the Scene.

This will still work, setting both the Slider Value and the Audio Mixer Group correctly, even if the Slider object is disabled.

Slider Settings Example Unity

Adding the Set Volume Script to a different object means that it loads the saved setting at the Start of the Scene, not only when you open the menu.

Slider Dynamic Float option missing in Unity 2019.2.5? Here’s How to fix it

If you don’t see the dynamic float option when selecting the On Value Changed event on the slider, check first that the Set Level function takes only a single float parameter, as this is usually the issue.

At the time of writing this, however, there’s a suspected issue in Unity 2019.2.5 where the Dynamic Float option just doesn’t appear.

You will still be able to select the Set Level function and it still fires every frame, it’s just not using the live slider value, instead it only passes a static parameter to the script, which is no good.

It’s more than likely that this is just a bug and will be fixed in a patch, or in a future version of Unity. Luckily, however, it can easily be fixed right now too, by slightly modifying the script.

How to fix the dynamic float issue in Unity 2019.2.5

In the example in this article, the SetLevel function takes the slider value as a parameter. This only works when you select the function from the Dynamic Float section of the list. As this option appears to be missing in Unity 2019.2.5 we instead need to remove the parameter from the function and just retrieve the slider value ourselves instead.

Here’s what the modified script looks like:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.UI;
public class SetVolume : MonoBehaviour
{
    public AudioMixer mixer;
    public Slider slider;
    void Start()
    {
        slider.value = PlayerPrefs.GetFloat("MusicVolume", 0.75f);
    }
    public void SetLevel()
    {
        float sliderValue = slider.value;
        mixer.SetFloat("MusicVol", Mathf.Log10(sliderValue) * 20);
        PlayerPrefs.SetFloat("MusicVolume", sliderValue);
    }
}

This new version of the script isn’t passed the slider value like it was before.

Instead it just retrieves it by getting slider.value at the start of the function, leaving everything else the same.

by John Leonard French

Game Composer & Sound Designer