Keeping audio from one scene to another on Unity

2

I need help.

I'm doing a 2D game on Unity. And I'd like to know how I can keep the audio (background music) from one scene to another and keep it from where it left off. And also how I would do to specify the scenes he should continue, and the scenes he should be destroyed.

    
asked by anonymous 11.07.2018 / 10:58

1 answer

3

To reproduce the audio of your background music, I assume you have a game object in the scene with an attached AudioSource component. To keep this object from existing over other scenes and keep it playing the same song, you can use a script that prevents it from being destroyed while loading scenes. It would look something like this:

class DontDestroyThis : MonoBehaviour {

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

Simple like this, create a C # script with the name DontDestroyThis and use this implementation in the Start method. Attach this script to the object that contains the AudioSource . All right, your background music will continue to play through the scenes.

To define which scenes you want to keep playing or not, you could have another script in each of the scenes that would make that management for you. Then you could use the Play, Stop, UnPause and Pause methods 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 refer to the script documentation of the AudioSource component directly on the Unity in>: link

    
11.07.2018 / 13:54