Music code not playing music.

I’m trying to play music fluently between my ‘MainMenu’ and ‘Settings’ scenes but the code I have wont play the music, it doesn’t show any errors and I can’t find anything wrong with the code.

Code:

//Keeps the music playing fludently throughout 'MainMenu' and 'Settings'
static bool AudioBegin = true;
void Awake()
{
    if (!AudioBegin)
    {
        Debug.Log("Music");
        GetComponent<AudioSource>().Play();
        DontDestroyOnLoad(gameObject);
        AudioBegin = true;
    }
}
void Update()
{
    if (Application.loadedLevelName == "MainScene")
    {
        Debug.Log("Music2");
        GetComponent<AudioSource>().Stop();
        AudioBegin = false;
    }
}

Well…
Someone would be
Try just creating a audio source

Public audioclio namehere;

audiosource secondname;

void Start()
{
secondname= GetComponent();
secondname.clip = namehere;

}

void yourstuffhere()
{
namehere.play()

}

Then use the loop function unity offers

to stop playing the music simply go with namehere.pause()

Im just a beginner myself but this could be something to experiment with.

The only point where music could be played is within the Awake-function. This function is called only once. Since your AudioBegin-Boolean is set to “true” at the beginning it will never play.

You should take a look at Unity’s Event execution order. I think using “OnLevelWasLoaded” could help. Using “Update” is not that good, since it is called ever frame. You don’t want to stop your music every frame.

You should take a look at this :

So you have 3 scenes :

  • MainMenu => music1
  • Settings => music1
  • MainScene => music2

What you need to do basically is :

 void Start()
 {
         GetComponent<AudioSource>().Play();
 }

But you should not try to keep your gameobject alive between the scenes with music1 and the scene with music2. First of all, just do a script that plays the music at Start, and set the correct audioSource in each scene.

Having music1 playing fluently between your 2 scenes is a next step.

I think that in my project, we have dealed with the time. If you quit your scene at time=4 you begin the music at time=4 in the next scene.

I am not sure about my project, if your problem is not too urgent or if you can’t find a solution, I can check that tomorrow. But dealing with objects that stay alive from one scene to another can be a bit tricky I guess, that is not something I recommand if you can avoid doing this.