- Home /
How would I have a volume bar in multiple places?
For example, at the menu, and at the pause menu... How?
What exactly do you mean by how? Do you mean how to synchronize the value between the two volume bars?
Do you already have the volume bar created and are just trying to get two different ones working together? Or are you also asking how to make a volume bar in general?
As in what code would make it so these happen
You are at the menu
you change the volume and it affects the audio
the volume bar now = the menu volume bar
AND VICE VERSA for the pause menu
You should look into playerprefs. This way you can also save the volume between sessions. http://docs.unity3d.com/ScriptReference/PlayerPrefs.html
Answer by Superrodan · Jan 17, 2015 at 01:08 AM
The way to do this is to have a variable you store somewhere globally. I did this with a playerprefs variable so that if I turned off the game and came back it would remember the volume I wanted.
So whenever they change the volume you determine what they changed it to and run this code:
PlayerPrefs.SetFloat("Volume", 0.75F);
The 0.75f in the above example would be whatever float they changed the volume to.
Additionally, whenever you load any screen with a volume bar on it you run this code:
float tempVolume = PlayerPrefs.GetFloat("Volume", 1.0F);
Instead of 1.0f in the above code you would put whatever you want the default volume to be. This code will return the volume that they set last time OR it will return the default volume if they have never set a volume.
Once you have run that code you just set your volume bar to the value of tempVolume.
does this work if the volume bars are in different scenes?
Yes. PlayerPrefs is stored externally. It basically writes it to a file somewhere on the device and pulls it from that file later.
PlayerPrefs is useful for saving things across scenes AND game sessions. With this code if you turn off the game and turn it back on it will remember what the volume was last time.
No problem. Don't forget that you also need to set the actual volume of your sound to the same variable.
Otherwise your volume bars will remember what the player set the volume to but the sound itself will not.