- Home /
Music will not change when an event triggers it
Cannot get my music to change when a boolean changes from false to true. The boolean is definitely changing, but the code itself is not activating the new track. Any ideas what may be causing this?
public class AudioManager : MonoBehaviour
{
public AudioSource BGM;
public AudioClip goTrack;
public bool gameOver = false;
void ChangeBGM(AudioClip music)
{
music = goTrack;
if(gameOver == true)
{
Debug.Log("Playing Game Over Music");
BGM.Stop();
BGM.clip = goTrack;
BGM.Play();
}
}
}
When is called ChangeBG$$anonymous$$
? Who calls it?
A very strange thing I don't understand is the following line:
music = goTrack;
Shouldn't it be
goTrack = music;
???
You are definitely correct, but unfortunately that did not make it work.
How about my 2 questions?
Do you see only one Playing Game Over $$anonymous$$usic
in the console? (make sure the Collapse
button is not turned on in the Console tab)
Answer by Spip5 · Jun 18, 2019 at 07:36 PM
@thexoy I'd suggest you create a singleton Instance for that AudioManager to get rid of this boolean.
public static AudioManager Instance;
void Awake() {
if (AudioManager.Instance) {
destroy(this);
} else {
Instance = this;
}
and then you call a function tho change your song
public void PlayGameOverSong() {
BGM.Stop();
BGM.clip = goTrack;
BGM.Play();
}
from another script with something like this
void ExternalFunction() {
AudioManager.Instance.PlayGameOverSong();
}
Hope that helps
Edit : To properly answer your question : a function isn't re-called unless you call it (except for Updates which is called every frame but can be a CPU eater if wrongly used). Changing your bool won't re-call your function., you would have to change the bool THEN re-call the function. Therefore your bool is not really necessary, just do a function that changes your song (see above).
Answer by PolyvivalStudios · Jun 18, 2019 at 07:17 PM
Are you calling the function from another script? It won't work otherwise. Or If you want it to check if the boolean is true or false all the time, put it in the update function.
Answer by TeriakiGames · Jun 18, 2019 at 08:01 PM
So the way an audio source work, is that it plays the sound when you want it to.
If you really want it to be successful. Try adding
Audio.stop(); Audiosource.clip = to your clip;
// Add line here if (audiosource.isPlaying() == false) { //Then play you`r tune. Audiosource.play();
}
Also check in the inspector to see if it is changing??.
Hope this helps
Your answer
Follow this Question
Related Questions
AudioClip Precise Timing and Delay 1 Answer
Sound issues 0 Answers
How to stop music from restarting when reloading scene it began? 0 Answers
Problem with enabling and playing audios 0 Answers
C sharp cant play Audio 2 Answers