PlayerPrefs defaulting to 0

Hi Guys, I can’t seem to fix this simple problem. When testing in editor or running a build for the first time, the music volume and SFX volume keeps defaulting to 0. This is my code. Am I doing something wrong?

function Start() {
	//Set SFX and Music Sliders to correct positions.
	if(!PlayerPrefs.HasKey("musicVolume")) PlayerPrefs.SetFloat("musicVolume",1);
	if(!PlayerPrefs.HasKey("sfxVolume")) PlayerPrefs.SetFloat("sfxVolume",1);
	var setMusicVolume = GameObject.Find("MusicSlider").GetComponent(UnityEngine.UI.Slider);
	setMusicVolume.value = PlayerPrefs.GetFloat("musicVolume");
	var setSfxVolume = GameObject.Find("SfxSlider").GetComponent(UnityEngine.UI.Slider);
	setSfxVolume.value = PlayerPrefs.GetFloat("sfxVolume");


I had a problem like this because the slider’s On Value Changed was set to “Editor and Runtime”.

What happened was this; after playing the scene the editor would display the slider in the scene window with a value of 0. This triggered my On Value changed handler (nb: Editor and Runtime) which would then save the editor’s 0 value for the slider into the player prefs.

Fix: Set the slider’s On Value Change to Runtime Only.

I discovered this by using logging. The value 0 was always saved to player prefs when I stopped running the game to return to the editor.

if(!PlayerPrefs.HasKey(“sfxVolume”)) PlayerPrefs.SetFloat(“sfxVolume”,1);
This will only set the float to 1 if the key does not exist. If the key exists (if you set it to 0 some time ago for example), it will do nothing.

setSfxVolume.value = PlayerPrefs.GetFloat("sfxVolume");

This will get the value, which was previously stored as 0.

You can clear playerprefs with DeleteKey or DeleteAll.

A nicer way to specify a default value, is to provide one when calling GetFloat.

setSfxVolume.value = PlayerPrefs.GetFloat("sfxVolume", 1);

Note that it’ll still return 0 until you delete the previous value you stored there.

So it turns out the problem was with the editor. Finding and deleting the player prefs file fixed this issue for me.

It might be that you’re passing an integer; try passing 1f or 1.0 to SetFloat.