How to save volume of audio source when game is restarted?
How do I save volume of my audio source (clicking the mute button) when game is restarted. You see I have one scene in my game and once the player dies there is a button the user can click on that resets the game, however it also resets the audio source, so when I play the game and click my mute button, the audio source volume is at 0 but when I die and click the reply button (the restart/reset button) the music is restarted as well, instead of staying muted (save the current volume). I tried using DontDestroyOnLoad(this) but my muted script is attached to my game over panel animation (the panel comes down when player dies) making the my game over panel animation not being destroyed when you restart the game. I tried other methods like putting my mute button script on a parent empty object and putting the object that has the audio source on under it as a child but it did the same thing. Anyway this is my mute button script:
private bool mute;
public void Muted ()
{
mute = !mute;
if (mute){
gameObject.GetComponent<AudioSource>().volume = 0;
}else
{
gameObject.GetComponent<AudioSource>().volume = 1;
}
}
}
And this is my restart level when button is pressed (p.s. I used the OnClick method activating methods):
public void NavigateTo(int scene)
{
Application.LoadLevel ("Game Level");
}
Thank you :)
Answer by thor348k · Aug 27, 2016 at 07:13 AM
You can save it to PlayerPrefs:
PlayerPrefs.SetInt("Volume", gameObject.GetComponent<AudioSource>().volume);
And then load it at the start of the scene:
gameObject.GetComponent<AudioSource>().volume = PlayerPrefs.GetInt("Volume");
Here's how I would do it:
private bool mute;
private AudioSource source;
private void Start()
{
// get the source, so you don't have to "Get" it each time
source = GetComponent<AudioSource>();
// if the volume has been saved before
if (PlayerPrefs.HasKey("Volume"))
{
// set the volume to saved volume
source.volume = PlayerPrefs.GetInt("Volume");
}
}
public void Mute()
{
mute = !mute;
if (mute)
{
source.volume = 0;
}
else
{
source.volume = 1;
}
// save the new volume
PlayerPrefs.SetInt("Volume", source.volume);
}
This is UNTESTED, I'm just typing in-browser. It's incomplete, but it will get the basic job done. For example, if the game is muted/saved, and then closed, when this is run when the game is opened, the game would be muted, or at least the audio source. You'd need to account for things like that.
If you don't want it to be persistent, you can use static variables, which are something like "global variables". Those won't be saved when the games closes, but will be kept while the game is running.
Here is a good Unity Tutorial on statics.
Good luck, hope this helps! :)