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.