Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Discussion My simplistic non-linear master volume slider

Discussion in 'Audio & Video' started by linenum, Oct 22, 2023.

  1. linenum

    linenum

    Joined:
    Nov 16, 2020
    Posts:
    44
    This is said to be the "right way"
    https://johnleonardfrench.com/the-r...slider-in-unity-using-logarithmic-conversion/

    It seems to involve setting all of the AudioSources to an AudioMixer. The slider is set from 0.0001 to 1 (0 is a problem).

    In the mixer it goes from -80 to 20 on a logarithmic scale....

    Their code:
    Code (CSharp):
    1. public void SetLevel(float sliderValue)
    2. {
    3.     mixer.SetFloat("MusicVol", Mathf.Log10(sliderValue) * 20);
    4. }

    My code:
    Code (CSharp):
    1.     void Start()
    2.     {
    3.         SetVolume(PlayerPrefs.GetFloat("masterVolume", 1f));
    4.     }
    5.  
    6.     public void SetVolume(float volume)
    7.     {
    8.         volumeSlider.value = volume;
    9.         float adjustedVolume = Mathf.Pow(volume, 2f); // square the value (power of 2)
    10.         AudioListener.volume = adjustedVolume;
    11.         soundVolumeText.text = (adjustedVolume * 100).ToString("0") + "%";
    12.         PlayerPrefs.SetFloat("masterVolume", volume);
    13.     }
    My slider goes from 0 to 2 with a default of 1. The text goes from 0% to 400%.

    AudioListener.volume is the global volume - no need to set up any mixer.

    You can make a reset button that calls SetVolume with a parameter of 1.
     
    Last edited: Oct 22, 2023