- Home /
Why does my background music get louder each time a scene is loaded
I have a GameObject with an Audio Source and the script below. This object only exists in the first level of my game. When the game starts the music starts playing. The problem I have is that each time I load a new level the sound gets louder. I don't understand why this is happening. Can someone explain why this is happening and give a possible solution?
using UnityEngine;
using System.Collections;
public class MusicManagerScript : MonoBehaviour
{
public AudioClip[] songs;
int currentSong = 0;
// Use this for initialization
void Start() {
DontDestroyOnLoad(gameObject);
}
// Update is called once per frame
void Update() {
if (audio.isPlaying == false) {
currentSong = currentSong % songs.Length;
audio.clip = songs[currentSong];
audio.Play();
currentSong++;
}
}
}
Answer by AlucardJay · Jul 06, 2013 at 05:35 AM
Check where your audio listeners are in each scene compared to the object with the above script. If you are not using 3D sounds for your songs, the volume will change depending on the distance to the audio listener (and the volume roll-off in the audio source).
Ah! I forgot to disable 3D sound on the songs and you are exactly right. The audio listeners were placed differently in each level. I disabled 3D sound and everything is working as intended. Thank you!
actual problem is not the 3D sounds, it is the DontDestroyOnLoad(gameObject);
the number of audio source increase by one everytime you load the scene.
Ins$$anonymous$$d remove DontDestroyOnLoad(gameObject); or do the following
public static $$anonymous$$usic$$anonymous$$anagerScript instance;
void Start()
{
if(instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
Absolutely, that could be the case, but the OP described change in volume rather than multiple audios playing over each other (they probably wouldn't be synchronized either, giving clear indication of more than one playing).
You are totally correct suggesting a singleton method. To the OP, Here's a link to (one of my) $$anonymous$$usic $$anonymous$$anager Singletons : http://answers.unity3d.com/questions/375227/music-continued-in-the-all-level.html
I actually came across the singleton method when trying to figure out what the problem was. I did implement it and nothing changed. The game object is only being created once. The camera was closer to the audio source on the "game over" level I created causing an increase in volume. I guess I will add the singleton method back to my music manager since it sounds like it is good practice.
Thank you for your help and extra information! :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613105559im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Theme music for approach to object question 1 Answer
Trigger Start of Sound 1 Answer
Sound effect doesn't play correctly 1 Answer