Using Slider 'On Value Changed'

Instead of updating music volume (or difficulty) in the Update method on every frame, it could be done with the on value changed event of the slider. That way it is only updated when the value actually changed. I also update the PlayerPrefs at the same time eliminating the need for the SaveAndExit functionality on the back button.

With an update method something like this

    public void UpdateVolume()
    {
        PlayerPrefsController.Volume = volumeSlider.value;
        SetMusicPlayerVolume();
    }

    private void SetMusicPlayerVolume()
    {
        if (!musicPlayer)
        {
            return;
        }

        musicPlayer.SetVolume(volumeSlider.value);
    }
5 Likes

Thank you!! :smile:

1 Like

Alternately, we can also use Slider.onValueChanged to invoke our method in scripts.
https://docs.unity3d.com/540/Documentation/ScriptReference/UI.Slider-onValueChanged.html

thanks to both @Vergil and @Anton_Nortje for these ideas. I must admit, having just learned a few lessons ago a reason not to put .Findobjectoftype<> in Update(), to see it happen here made me a bit confused.

   void Start() { 
 

        audiosource = GetComponent<AudioSource>();
        PlayerPrefsController.SetMasterVolume(0.5f);
        volumeSlider.value = PlayerPrefsController.GetMasterVolume();
        audiosource.volume = PlayerPrefsController.GetMasterVolume();
        volumeSlider.onValueChanged.AddListener(delegate { VolumeValueChangeCheck(); }); ;
    }

    public void VolumeValueChangeCheck()
    {
        PlayerPrefsController.SetMasterVolume(volumeSlider.value);
        audiosource.volume = PlayerPrefsController.GetMasterVolume();
    }

Hey for me it worked to do the above as well, adding a listener.

Privacy & Terms