- Home /
How to STOP music when loading a SPECIFIC SCENE?
Hi there - I have background music on my main menu, which continues playing through each menu. However, when I load my first level, I want this music to stop. I have tried a few methods of solving this, but haven't been able to get a working fix. Any help would be hugely appreciated! :D
Here's my code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class MusicPlay : MonoBehaviour { public static MusicPlay musicplay; public GameObject music;
void Awake()
{
if (musicplay == null)
{
DontDestroyOnLoad(gameObject);
musicplay = this;
}
else if (musicplay != this)
{
Destroy(gameObject);
}
}
}
Answer by Llama_w_2Ls · Jan 12, 2021 at 07:00 PM
In the update of this script, or preferably in the Start method of another script, you could destroy the music object when entering a specific scene. For example:
void Update()
{
Scene currentScene = SceneManager.GetActiveScene();
if (currentScene.name == "Level1")
{
// Stops playing music in level 1 scene
Destroy(gameObject);
}
}
Answer by Um4yr · Jul 29, 2021 at 09:02 PM
@Llama_w_2Ls i just have this, how do i make it stop playing this music when it switched scenes?
Answer by Bunny83 · Jul 30, 2021 at 08:18 AM
Don't use scene names in a script that is attached to an object in a different scene. Since your "MusicPlay" script is a singleton like object, you only have to add another tiny script which actually does the "stopping" or "starting" when the scene is loaded. For example
// BackgroundMusicHandler.cs
using UnityEngine
public class BackgroundMusicHandler : MonoBehaviour
{
public enum Mode {EnsurePlaying, Restart, Stop};
public Mode mode;
void Start()
{
if (mode == Mode.EnsurePlaying)
MusicPlay.musicplay.StartBackgroundMusic(false);
else if (mode == Mode.Restart)
MusicPlay.musicplay.StartBackgroundMusic(true);
else if (mode == Mode.Stop)
MusicPlay.musicplay.StopBackgroundMusic();
}
}
In your "MusicPlay" script you should add those two mentioned methods. Your MusicPlay script should probably cache the AudioSource that is attached to the MusicPlay script so it can easily access the audio source. So it would look something like this:
public class MusicPlay : MonoBehaviour
{
public static MusicPlay musicplay;
// either set backgroundMusic in the inspector or use GetComponent in Awake to initialize this variable
public AudioSource backgroundMusic;
void Awake()
{
if (musicplay == null)
{
DontDestroyOnLoad(gameObject);
musicplay = this;
}
else if (musicplay != this)
{
Destroy(gameObject);
}
}
public void StartBackgroundMusic(bool aRestart)
{
if (!backgroundMusic.isPlaying || aRestart)
backgroundMusic.Play();
}
public void StartBackgroundMusic()
{
backgroundMusic.Stop();
}
}
Now you can simply attach the "BackgroundMusicHandler" to any object in each scene and decide if you want to play background music, if you want to restart it or if you want to stop it.