Home > Software engineering >  How can I change the background music from one scene to another?
How can I change the background music from one scene to another?

Time:12-25

There are only two scenes in my game. The first is the menu and the second is the game. In the second scene I added background music and I made sure that when reloading the scene the music did not interrupt, but this means that when returning to the menu the music continues overlapping that of the menu.

Can you give me any solutions please? Thank you!

This is the code to make the music continue with the scene reloads:

using UnityEngine;
using UnityEngine.SceneManagement;

public class BackgroundMusic : MonoBehaviour
{
    private static BackgroundMusic backgroundMusic;
    
    void Awake()
    {
    
       if (backgroundMusic == null)
        {
            backgroundMusic = this;
            DontDestroyOnLoad(backgroundMusic);
            Debug.Log(SceneManager.GetActiveScene().name);
        }
        else
        {
            Destroy(gameObject);
        }
    }

}

CodePudding user response:

Put the same game object with the BackgroundMusic script on both of the scenes. Since you implemented the singleton pattern, this will ensure that only 1 music player will ever play at one time.

Now, subscribe to SceneManager.sceneLoaded so that you can change the music based on the scene, like so:

using UnityEngine.SceneManagement;

public class BackgroundMusic : MonoBehaviour
{
    private static BackgroundMusic backgroundMusic;

    void Awake() 
    { 
        // Keep singleton pattern implementation here 
        SceneManager.onSceneLoaded  = SwitchMusic;
    }

    void SwitchMusic()
    {
        // Logic to change music tracks here.
        // You could have an array of AudioClip and index 
        // that array by the scene's build index, for instance.

        // You can also just check if scenes actually changed, and if not,
        // you can make the music just continue without changing.
    }
}

Let me know in the comments if you have any questions.

  • Related