using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ChangeMusicVolume : MonoBehaviour {
public Slider Volume;
public AudioSource myMusic;
// Update is called once per frame
void Update () {
myMusic.volume = Volume.value;
}
}
I’m trying to make my menu’s volume slider control the volume of every scene in the game. The above code works great! But only works in the menu… help please? For a complete beginner?
Edit: Also, does anyone know how to make the volume start at midway instead of 0?
Add a Start() function and put in there:
DontDestroyOnLoad( gameObject);
and then that slider will remain visible through the life of the game, as long as you start from the main menu.
Trouble is, it will be double-loaded when you get back to the main menu, so best to stick it in a “pre-menu” scene that only ever loads once.
Also if you want it at halfway, in that same Start() function set it:
Volume.value = 0.5f;
A solution I’ve written up for a couple of people is to have your music slider set the sound in the main menu.
Now, in other scenes you can have a script that has a reference to each audio source.
Using PlayerPrefs, you store the volume from the menu scene.
In Start() on the scripts, in each scene, you load the value and then go over the list of all reference audio sources and set the volume.
This can work with just 1 audio setting (for music, say), or for more than 1 (say music volume + sound effects volume); it would just require 2 saved volumes and 2 different lists, in that case.
This design, written as-is, needs a unique scene for changing the volume, because it relies on Start() running on new scenes, but it could be modified a bit, to have an in-game menu to do that same.
Now that I think about it, this could be a good time for a scriptable object reference for the sound settings.