How to keep audio from one scene to another in Unity

Asked

Viewed 1,014 times

2

I need help.

I’m playing a 2D game at Unity. And I would like to know how to keep the audio (background music) from one scene to another and that it continues where it left off. And also how I would specify the scenes he must continue, and the scenes he must be destroyed.

1 answer

3

To play audio from your background music I assume you have one game Object on the scene with a Audiosource attached. To keep this object existing throughout other scenes and keep it playing the same music, you can utilize a script that prevents it from being destroyed while loading scenes. It would be something like this:

class DontDestroyThis : MonoBehaviour {

    void Start()
    {   
        // Este método impede que o objeto 
        // atual seja destruido durante o carregamento.
        DontDestroyOnLoad(gameObject);
    }
}

Just like that, create a C# script with the name Dontdestroythis and use this implementation in the method Start. Attach this script to the object containing the Audiosource. Ready, your background music will continue playing throughout the scenes.

To define which scenes you want it to continue playing or not, you could have another script in each of the scenes that would make this management for you. So you could use the methods Play, Stop, Unpause and Pause to control audio playback. Example:

using UnityEngine.SceneManagement;
class AudioManagerExample : MonoBehaviour
{
    private void Start()
    {
        // Obtém o objeto da cena que possui o AudioClip
        // é bom manter uma convenção para o nome deste objeto.
        // Neste exemplo BGM.
        GameObject audioSourceGameObject = GameObject.Find("BGM");

        // Obtém o componente AudioSource do objeto.
        AudioSource source = audioSourceGameObject.GetComponent<AudioSource>();

        // Utilize as linhas abaixo conforme necessário
        // para controlar a reprodução.
        source.Play();      // Inicia a reprodução do áudio.
        source.Stop();      // Pára a reprodução do áudio, inicia do começo quando for reproduzido novamente.
        source.UnPause();   // Despausa a reprodução previamente pausada. Similar ao Play após um audio ter sido pausado.
        source.Pause();     // Pausa a reprodução.

        // Exemplo:
        if(SceneManager.GetActiveScene().name == "NomeDaCenaDesejada")
        {
            source.Play();
        }
        else
        {
            source.Stop();
        }
    }
}

For more information, you can consult the documentation of API of script of the component Audiosource directly on the website of Unity: https://docs.unity3d.com/ScriptReference/AudioSource.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.