Struggling to understand the Playerprefs system.

Hello all! I’m new to working with the Unity program, and I’ve been working on making a project recently and I’m currently following guides for making an options menu. When it came time to work on the audio settings, I just got completely stuck. I’ve spent a couple of hours now perusing forums regarding using Playerprefs to save audio settings between sessions of a game, but I just am having no luck. Currently, I’m just working on getting the master volume setting to save so that once that’s working I can apply that same code to music and SFX with appropriate adjustments. I’m working in Unity 2021.3.11f1 if that makes a difference, and from what I’ve figured using a Playerprefs key viewer from the asset store it seems like my program just isn’t properly saving an actual value? It just saves the key itself, which isn’t exactly helpful… Below is what my code looks like for my audio options including all the relevant info I can think of. I also attached the PlayerPrefsEditor window showing exactly what data is being saved to them:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;

public class OptionsMenu : MonoBehaviour
{
    public Toggle fullscreenTog, vsyncTog;

    public ResItem[] resolutions;

    private int selectedResolution;

    public TMPro.TextMeshProUGUI resolutionLabel;

    public AudioMixer theMixer;

    public Slider masterSlider, musicSlider, sfxSlider;
    public TMPro.TextMeshProUGUI masterLabel, musicLabel, sfxLabel;
    public float masterVolume, musicVolume, sfxVolume;

    public AudioSource sfxLoop;
   
    public

    // Start is called before the first frame update
    void Start()
    {
        fullscreenTog.isOn = Screen.fullScreen;

        if(QualitySettings.vSyncCount == 0)
        {
            vsyncTog.isOn = false;
        }
        else
        {
            vsyncTog.isOn = true;
        }

        //search for resolution in list
        bool foundRes = false;
       
        for(int i=0; i < resolutions.Length; i++)
        {
            if(Screen.width == resolutions[i].horizontal && Screen.height == resolutions[i].vertical)
            {
                foundRes = true;

                selectedResolution = i;

                UpdateResLabel();
            }
        }

        if (!foundRes)
        {
            resolutionLabel.text = Screen.width.ToString() + " x " + Screen.height.ToString();
        }

        theMixer.SetFloat("MasterVol", Mathf.Log10(PlayerPrefs.GetFloat("MasterVol", 1) * 20));

    }

    // Update is called once per frame
    void Update()
    {
      
    }

    public void ResLeft()
    {
        selectedResolution--;
        if(selectedResolution < 0)
        {
            selectedResolution = resolutions.Length - 1;
        }

        UpdateResLabel();
    }

    public void ResRight()
    {
        selectedResolution++;
        if(selectedResolution > resolutions.Length - 1)
        {
            selectedResolution = 0;
        }

        UpdateResLabel();
    }

    public void UpdateResLabel()
    {
        resolutionLabel.text = resolutions[selectedResolution].horizontal.ToString() + " x " + resolutions[selectedResolution].vertical.ToString();
    }

    public void ApplyGraphics()
    {
        //apply fullscreen
        //Screen.fullScreen = fullscreenTog.isOn;

        if (vsyncTog.isOn)
        {
            QualitySettings.vSyncCount = 1;
        }
        else
        {
            QualitySettings.vSyncCount = 0;
        }

        //set resolution

        Screen.SetResolution(resolutions[selectedResolution].horizontal, resolutions[selectedResolution].vertical, fullscreenTog.isOn);

    }

    public void SetMasterVol(float sliderValue)
    {

       
        //masterLabel.SetText($"{sliderValue:F0)}");

        theMixer.SetFloat("MasterVol", Mathf.Log10(sliderValue) *20);
       
       
        PlayerPrefs.SetFloat("MasterVol", sliderValue);

        masterLabel.text = (sliderValue * 100).ToString("F0");

       
       
        PlayerPrefs.Save();
      
    }

    public void SetMusicVol()
    {
        musicLabel.text = (musicSlider.value * 100).ToString("F0");

        theMixer.SetFloat("MusicVol", Mathf.Log10(musicSlider.value) *20);

        PlayerPrefs.SetFloat("MusicVol", musicSlider.value);
    }

    public void SetSFXVol(float sliderValue)
    {
        sfxLabel.text = (sfxSlider.value * 100).ToString("F0");

        theMixer.SetFloat("SFXVol", Mathf.Log10(sliderValue) *20);

        PlayerPrefs.SetFloat("SFXVol", sliderValue);
    }

    public void PlaySFXLoop()
    {
        sfxLoop.Play();
    }

    public void StopSFXLoop()
    {
        sfxLoop.Stop();
    }

   
}

[System.Serializable]
public class ResItem
{
    public int horizontal, vertical;
}

PlayerPrefs are super-easy when you wrap them up properly. (See below).

Try wrapping them so you can treat them just like regular static / global variables, and if it doesn’t fix your problem then you have a bug somewhere ELSE than PlayerPrefs and you can debug for it (see below).


Here’s an example of simple persistent loading/saving values using PlayerPrefs:

Useful for a relatively small number of simple values.


If you need to debug, first you must find a way to get the information you need in order to reason about what the problem is.

Don’t assume the problem is in PlayerPrefs, as I noted above.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Does the missing value persist after you reopen the PlayerPref viewer window (or restart the editor)? I’ve never used that viewer before, and I could believe that it gets confused if a variable is added while the viewer is open.

Yeah, it stays open between instances of running the editor. It is possible it’s getting stuck when the values are updated but I’m not 100% sure. I am gonna keep fiddling with it and see what happens.

Thanks for all of the information! I’ve started implementing the Debug.Log function to my code from time to time, but it never crossed my mind to take this degree of an approach with it up until now! I’ll have to keep working with it and seeing what happens, will update as I find out what’s been going on with it!

It worked!! Thank you so much for your advice!! with all of the details being logged in the debug log, just like you said it took no time at all to find the problem and subsequently solve it, and with barely a half hour if even that of troubleshooting, the audio options are working exactly as intended! Once again thank you so much for your help, the concise and detailed information made solving this so much easier than I could have ever fathomed!

1 Like

That’s awesome… I encourage you to throw yourself in fully, gamedev in Unity is SO much fun.

It really has been! I started this course to add on to another course I was working on, with the end goal being to take a few courses and convert that knowledge into my own fully functioning game! And I’m so thankful for people like you hanging out on the forums helping newbies like myself figure it all out!

1 Like