How to stop music in next scene after using dontdestroyonload

Hi everyone!

I’m a kind of newbie in Unity and C#. I’m making a little project. In the game at the end of each level it appears a minigame with a scene change. The minigame consists in guessing a word between 3 options. If you fail, the scene of minigame reload, but if you win it comes the next scene. So I want the music of the minigame to no reload if you fail, so I have used this:

void Awake()
{
    GameObject[] musicObj = GameObject.FindGameObjectsWithTag("Neologism1");
    if (musicObj.Length > 1)
    {
        Destroy(this.gameObject);
    }
    DontDestroyOnLoad(this.gameObject);
}

Ant it works perfectly. The problem is that if you win guessing the word, the next scene is loaded, but also the music from the minigame. That is I want the music from the minigame to stop if you guess the word. Sorry if it is something to obvious that I have’nt seen. I’ve thought about using scriptable objects, but it seems to me too simple to use them. Also trying to combine with scenemanagement, but with no working results.

Thanks a lot in advance and have a nice day!

I am gonna answer based on the assumption I have made, correct me if I am wrong here.

  1. You are in a Minigame scene and whenever you fail it reload and you don’t want the music to be interrupted.
  2. When you successfully complete the minigame you go to the next level.

Based on this you can have the following logic:
You can have a script which manages the Audio files (an AudioManager for example). This can keep a list of background music you want to play for each scene.
Make this script don’t destroy on load.

Now what you need is a function which will detect whether you are in the same scene or you have switched to a different scene.
You can either have the same script do that or create a separate script which tracks the scenes(which will be better in the long run).

Here is a pseudo code for the same

public class AudioManger: MonoBehaviour
{
    public static AudioManager Instance;
    public List<AudioClip> backgroundMusic;
    private int currentScene;
    private AudioSource audioSource;
    void Awake()
    {
       //Making a Singleton
        if(Instance==null)
            Instance = this;
        else 
            Destroy(this.gameObject);
        currentScene = 0;
        audioSource = GetComponent<AudioSource>();
    }
    //.......
   //This function can be called by the script which handles the level change
    public void UpdateScene(int scene)
    {
        //if scene did not change then don't do anything
        if(scene == currentScene)
            return;
        //Update the Background Music AudioSource based on the scene
        audioSource.clip = backgroundMusic[scene];
        audioSource.Play();
    }
}

Yep, that’s exactly what I want! Thanks a lot. I think about the audio manager and scriptable objects, but have thinked could be a less “complicated” way. Nonetheless, thank you very much again!