Possible Bug in Lecture Code?

I noticed a bug with the music in the game. My volume settings were saving correctly but whenever I exited the game and started it again the volume went back to its default levels. The volume only changed to the player pref level when I accessed the options screen. This is because when the game initially loads the music player is not setting the volume to what’s in the player prefs. I added the following line to the OnlevelWasLoaded(int level) method in the MusicManager class:

audioSource.volume = PlayerPrefsManager.GetMasterVolume();	

This fixed my problem. The full method looks like this:

	private void OnLevelWasLoaded(int level)
{
	Debug.Log("Playing clip: " + levelMusicChangeArray[level]);
	var thisLevelMusic = levelMusicChangeArray[level];
	
	if(thisLevelMusic)
	{					
		audioSource.volume = PlayerPrefsManager.GetMasterVolume();	
		audioSource.clip = thisLevelMusic;
		audioSource.loop = true;
		audioSource.Play();
	}
}
8 Likes

Thank you for sharing this.

2 Likes

There’s one more issue with this. GetMasterVolume needs to return the default level if the PlayerPrefs don’t exist. (ie first time game is ever launched)

Or the default PlayerPrefs should be stored automatically when the game starts, if none exist… so it will then read the defaults on the start screen.

3 Likes
audioSource.volume = PlayerPrefsManager.GetMasterVolume();	

You can actually add this line of code to the start function since it is controlling all music so that you only access your PlayerPrefsManager once when the Persistent Music Manager is first initialized.

Also, if you change the volume in the inspector for Persistent Music Manager it will use that volume setting for the very first time the game ever runs since the game will not have had a chance to write a value to the PlayerPrefsManager yet. This means that if you want your default volume to be 0.8f as covered in the lesson you should set it to that value in the inspector.

Privacy & Terms