Search code examples
c#unity-game-engineaudio-player

Background music destroyed when build index is 0


I've got this background sound playing throughout the game. The problem is that I want it to stop when the scene index is 0.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class BackgroundMusic : MonoBehaviour
{

void Start()
{
    GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
    if (objs.Length > 1)
    {
        Destroy(this.gameObject);
    }
    if (SceneManager.GetActiveScene().buildIndex != 0)
    {
        DontDestroyOnLoad(this.gameObject);
    }

}

I've been using this script but still doesn't work Any suggestions?


Solution

  • If you use DontDestroyOnLoad it is "forever" you don't have to do it for each scene again.

    And then note that after that the Start is not called for every scene load again only the first time!

    Rather use SceneManager.sceneLoaded like e.g.

    public class BackgroundMusic : MonoBehaviour
    {
    
        private static BackgroundMusic _instace;
    
        private void Awake()
        {
            if (_instance && _instance != this)
            {
                Destroy(this.gameObject);
                return;
            }
            
            DontDestroyOnLoaddd(this.gameObject);
            _instance = this;
    
            SceneManager.sceneLoaded += OnSceneLoaded;
        }
    
        private void OnDestroy ()
        {
            SceneManager.sceneLoaded -= OnSceneLoaded;
        }
    
        private void OnSceneLoaded (Scene scene, LoadSceneMode mode)
        {
            if(scene.buildIndex == 0)
            {
                // TODO disable música
                // NOTE: I wouldn't Destroy this though but rather only stop the music
            }
            else
            {
                // TODO enable the music
            }
        }
    }