How to set a Mixer's volume to a slider's volume in Unity?

Qedized picture Qedized · Oct 2, 2017 · Viewed 7.5k times · Source

I'm trying to make some audio settings. Here is my script:

public AudioMixer masterMixer;
public float masterLvl;
public float musicLvl;
public float sfxLvl;

public void SetMasterVolume ()
{
    masterLvl = masterVolumeSlider.value;
    masterMixer.SetFloat("masterVol", masterLvl);
}

public void SetMusicVolume()
{
    musicLvl = musicVolumeSlider.value;
    masterMixer.SetFloat("musicVol", musicLvl);
}

public void SetSfxVolume()
{
    sfxLvl = sfxVolumeSlider.value;
    masterMixer.SetFloat("sfxVol", sfxLvl);
}

It has all the OnValueChanged(); things on the sliders. I just want to know why this doesn't work. Thanks.

EDIT: So the thing is that it changes the dB, not the volume. The new question is: How do I make it change the volume instead of dB?

EDIT 2: Screenshot. audiomixer screenshot

Answer

Bodix picture Bodix · Jun 20, 2018

I think, your problem is that the mixer value (-80db - 20db) is a logarithmic scale and the slider value is linear. For example: half volume is actually about -10db, but if you connect it to a linear scale, like the slider, then half volume will end up being -40db! Which is why it sounds like it's basically silent at that point.

There's an easy way to fix it:

  1. Instead of setting the slider min / max values to -80 and 20, set them to min 0.0001 and max 1.

  2. In the script to set the value of the exposed parameter, use this to convert the linear value to an attenuation level:

     masterMixer.SetFloat("musicVol", Mathf.Log10(masterLevel) * 20);
    

It's important to set the min value to 0.0001, otherwise dropping it all the way to zero breaks the calculation and puts the volume up again.

Post:

https://forum.unity.com/threads/changing-audio-mixer-group-volume-with-ui-slider.297884/