Search Unity

Volume slider - master volume for all scenes

Discussion in 'Scripting' started by marom123, Jul 2, 2020.

  1. marom123

    marom123

    Joined:
    Jun 28, 2020
    Posts:
    1
    So I'm working now on my first game and I created a menu with an options section. In the options I have a volume slider that controls the music only on the menu. I want this slider to control the volume on all scenes. the script that I created for saving the volume:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class SliderVOL : MonoBehaviour
    7. {
    8.     public Slider slider;
    9.  
    10.     public void Start()
    11.     {
    12.         slider.value = PlayerPrefs.GetFloat("value", 1);
    13.     }
    14.     public void Update()
    15.     {
    16.         PlayerPrefs.SetFloat("value", slider.value);
    17.     }
    18.  
    19. }
    20.  
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    So.. what is the intention behind this post? Do you require help with something? If so, with what?

    Is this a showcase? If so, there is plenty to improve with this approach, as it's not a good idea to just write to PlayerPrefs each frame. Normally during runtime you want to keep data in a variable (potentially static if it is supposed to persist scenes), and save to playerprefs when quitting the application or changing scenes.
    Another approach would be to save to playerprefs when the value is actually being changed. This can either be achieved by remembering the last value and only writing to playerprefs if it changes between frames - or even better attaching a listener to the slider value to be notified when it changed, and then (and only then) saving the value.

    In my opinion the best approach would be to listen to a change in slider value, which you then write to a static variable, which you save to PlayerPrefs on application quit, and load once on start up. You can now also use this masterVolume static variable in your multiplications (for example with other audio slider values, like musicVolume) to determine the actual volume for any given audio source.
     
    Last edited: Jul 2, 2020