Search code examples
c#unityscriptunity-game-engine

Save sound value PlayerPrefers


I have a UI MENU where the player can set the volume of the game music.

Through a slider it can change the volume. I'm trying to save these values, and retrieves them whenthe game is open again, but without success so far.

When we change the value of the Slider, the sound also changes, but these values are not being saved.

My code looks like this:

Ps: 0 warning in Unity console, and C# answer if possible =]

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class PauseCanvas : MonoBehaviour
{
    public Button resumeButton;
    public Button backToMainMenuButton;
    public Button exitGameButton;

    public Canvas gameCanvas;
    public Canvas mainMenuCanvas;

    public Slider slider;

    public float startVolume = 1f;
    public float currentVolume;
    string newVolume;

    void Awake () {

        slider.value = GetComponent<AudioSource> ().volume;
        currentVolume = slider.value;

    }

    void Start () {

        startVolume = PlayerPrefs.GetFloat (newVolume, 1);
    }

    void UpdateVolume() {

        if (currentVolume < startVolume ) {
            PlayerPrefs.SetFloat (newVolume, currentVolume);
            PlayerPrefs.Save ();
        }
    }

    void OnEnable ()
    {
        //Register Button Events
        resumeButton.onClick.AddListener (() => buttonCallBack (resumeButton));
        backToMainMenuButton.onClick.AddListener (() => buttonCallBack (backToMainMenuButton));
        exitGameButton.onClick.AddListener (() => buttonCallBack (exitGameButton));
    }

    private void buttonCallBack (Button buttonPressed)
    {
        //Resume Button Pressed
        if (buttonPressed == resumeButton) {  
            Time.timeScale = 1;
            //Hide this Pause Canvas
            gameObject.SetActive (false);

            //Show Game Canvas
            gameCanvas.gameObject.SetActive (true);
        }

        //Back To Main Menu Button Pressed
        if (buttonPressed == backToMainMenuButton) {
            //Hide this Pause Canvas
            gameObject.SetActive (false);

            //Show Main Menu Canvas
            Score.Inicializar (); 
            SceneManager.LoadScene ("Menu");
        }

        //Exit Game Button Pressed
        if (buttonPressed == exitGameButton) {
            #if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
            #else
            Application.Quit();
            #endif
        }
    }

    void OnDisable ()
    {
        //Un-Register Button Events
        resumeButton.onClick.RemoveAllListeners ();
        backToMainMenuButton.onClick.RemoveAllListeners ();
        exitGameButton.onClick.RemoveAllListeners ();
    }
}

Solution

  • There are 2 problems in your code.

    1.UpdateVolume() is not being called anywhere in the script so there is no way to save the Slider value.

    2.string newVolume; newVolume is not initialized. So doing PlayerPrefs.SetFloat(newVolume, currentVolume); is thesame as PlayerPrefs.SetFloat(null, currentVolume); which is bad.

    The key that is passed in to SetFloat should not be null or empty. PlayerPrefs.SetFloat("something",currentVolume); or string newVolume = "something"; PlayerPrefs.SetFloat(newVolume, currentVolume); are both fine.

    You need a way of detecting when the slider value changes so that you can save the score. You can do with slider.onValueChanged.AddListener(delegate { sliderCallBack(slider); });

    Your whole code should like something below.

    public class PauseCanvas : MonoBehaviour
    {
    
        public Button resumeButton;
        public Button backToMainMenuButton;
        public Button exitGameButton;
    
        public Canvas gameCanvas;
        public Canvas mainMenuCanvas;
    
        public Slider volumeSlider;
    
        public float startVolume = 1f;
        public float currentVolume;
    
        string newVolume = "VOLUME_SLIDER"; //Can change to whatever you want as long as it is not null or empty
    
    
        void Start()
        {
            //Load volume from prevois saved state. If it does not exist, use 1 as default
            volumeSlider.value = PlayerPrefs.GetFloat(newVolume, 1);
            currentVolume = volumeSlider.value;
        }
    
        void UpdateVolume(float _volume)
        {
            currentVolume = _volume;
    
            PlayerPrefs.SetFloat(newVolume, _volume);
            PlayerPrefs.Save();
        }
    
        void OnEnable()
        {
            //Register Button Events
            resumeButton.onClick.AddListener(() => buttonCallBack(resumeButton));
            backToMainMenuButton.onClick.AddListener(() => buttonCallBack(backToMainMenuButton));
            exitGameButton.onClick.AddListener(() => buttonCallBack(exitGameButton));
    
            //Register Slider Events
            volumeSlider.onValueChanged.AddListener(delegate { sliderCallBack(volumeSlider); });
        }
    
        private void sliderCallBack(Slider sliderMoved)
        {
            //Volume Slider Moved
            if (sliderMoved == volumeSlider)
            {
                UpdateVolume(sliderMoved.value);
            }
        }
    
        private void buttonCallBack(Button buttonPressed)
        {
            //Resume Button Pressed
            if (buttonPressed == resumeButton)
            {
                Time.timeScale = 1;
                //Hide this Pause Canvas
                gameObject.SetActive(false);
    
                //Show Game Canvas
                gameCanvas.gameObject.SetActive(true);
            }
    
            //Back To Main Menu Button Pressed
            if (buttonPressed == backToMainMenuButton)
            {
                //Hide this Pause Canvas
                gameObject.SetActive(false);
    
                //Show Main Menu Canvas
                //Score.Inicializar();
                SceneManager.LoadScene("Menu");
            }
    
            //Exit Game Button Pressed
            if (buttonPressed == exitGameButton)
            {
    #if UNITY_EDITOR
                UnityEditor.EditorApplication.isPlaying = false;
    #else
                Application.Quit();
    #endif
            }
        }
    
        void OnDisable()
        {
            //Un-Register Button Events
            resumeButton.onClick.RemoveAllListeners();
            backToMainMenuButton.onClick.RemoveAllListeners();
            exitGameButton.onClick.RemoveAllListeners();
    
            //Un-Register Slider Events
            volumeSlider.onValueChanged.RemoveAllListeners();
        }
    }