Hi,
I’ve added a Sound Toggle option at the settings of the game. When the sound is toggled ON or OFF, the value 1 or 0 is stored in the PlayerPrefs. While opening the game scene, the Start method checks the value of the PlayerPrefs and sets the AudioListener.volume to 0 or 1. But, when I start the game for the first time, the sound is muted. When I go back to the Menu again, and come back to game, the sound plays correctly.
While the game is running for the first time, I added a Debug.Log to check the AudioListener.volume and AudioListener.pause and they were 1 and false respectively, which means that the sound should play, but it isn’t.
Also, I should mention that the game has a feature in the Menu, where I can clear all PlayerPrefs and set some of them to default values, which includes the sound state being set to 1 (means ON). The problem even re-appears during the first gameplay after a PlayerPrefs reset.
I don’t know what’s wrong with my code or anything that prevents the audio being played when the game is run for the first time, or after a PlayerPrefs reset.
Note: there is only one AudioListener in the scene, and the sounds work correctly from the second gameplay.
This is in the game scene script:
void Start()
{
//Turn On-Off Sound
if (PlayerPrefs.GetInt("SoundState") == 0)
{
AudioListener.volume = 0.0f;
Debug.Log(AudioListener.volume);
Debug.Log(AudioListener.pause);
}
else
{
AudioListener.volume = 1.0f;
Debug.Log(AudioListener.volume);
Debug.Log(AudioListener.pause);
}
}
This is in the Menu script:
void Start()
{
InitializePrefs();
//Turn On-Off Sound
if(PlayerPrefs.GetInt("SoundState") == 0)
{
AudioListener.volume = 0.0f;
}
else
{
AudioListener.volume = 1.0f;
}
}
public void ResetPrefs()
{
PlayerPrefs.DeleteAll();
InitializePrefs();
}
void InitializePrefs()
{
if (!PlayerPrefs.HasKey("SoundState"))
{
PlayerPrefs.SetInt("SoundState", 1);
}
}