Question by
madslh_unity · May 21, 2020 at 10:04 AM ·
audioaudiosourcevolume
Change audio volume of song depending on scene.
I am trying to make the volume for my music be loud in the main menu and in the game over scenes, and then a little less loud in the actual gameplay. I have used a singleton to make sure the music plays through all scenes, and that works fine. I then tried making some way to control when the scene changes, and that works fine as well. But when I try to change the volume of each scene, I don't get an error in visual studio, and through Debug.Log I can see that something does indeed change. But when I go to unity I got an error (with the previous code I tried) and now I don't get an error but the volume itself doesn't change.
This is my relevant code - it is attached to a GameObject with AudioSource where a song is in the audioclip:
AudioSource myAudioSource;
void Start()
{
myAudioSource = GetComponent<AudioSource>();
float audioVolume = myAudioSource.volume;
//on first scene
audioVolume = 1f;
// on the next scene
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnSceneLoaded(Scene arg0, LoadSceneMode arg1)
{
Scene currentScene = SceneManager.GetActiveScene();
string sceneName = currentScene.name;
if (sceneName == "Game")
{
float audioVolume = myAudioSource.volume;
audioVolume = 0.4f;
Debug.Log(audioVolume);
}
else
{
float audioVolume = myAudioSource.volume;
audioVolume = 1f;
Debug.Log(audioVolume);
}
}
Comment