how to pause and resume music after pausing game?

Hi

How can I pause the music when pausing the game and let it resume when I go back to the game?

I tried this script but the music resumes when I release the button.

function Update(){

if(Input.GetKeyDown(KeyCode.Escape)) {

audio.Pause();

}

if(Input.GetKeyUp(KeyCode.Escape)) {

audio.Play();

}

pretty simple solutions:

1- Assuming you using Time.TimeScale to pause your game you do this.

void Update()
{ 
  if(Input.GetKeyDown(KeyCode.Escape))
   {
      if(Time.TimeScale > 0)
       {
            Time.TimeScale = 0;
             audio.Pause();
        }
       else
        {
                Time.TimeScale = 1;
                 audio.Play();
         }
     }//input

}//update

This will pause/unpause your game and the audio.


2- if you handle the pause game on some other script then just:

    void Update()
    { 
      if(Input.GetKeyDown(KeyCode.Escape))
       {
          if(audio.isPlaying())
                 audio.Pause();
           else
                  audio.Play();           
       }//input
    }//update

function Update ()
{
if (gamePaused == true)
{
audio.mute = true;
}

else if (gamePaused == false)
{
audio.mute = false;
}

This is the best way I found to handle this situation.

@korial1

In unity 5 to resume a music after pause game you can use the function UnPause();

If the audio is in camera for example:

if(Input.GetKeyDown(KeyCode.Escape)) {
//audio.Pause();
Camera.main.GetComponent<AudioSource>().Pause();
}

if(Input.GetKeyUp(KeyCode.Escape)) {
//audio.UnPause();
Camera.main.GetComponent<AudioSource>().UnPause();
}

I’m using unity v5.3.5f1 and this works to me.

Just add a boolean system:

var gamePaused = false;

function Update(){

if(Input.GetKeyDown(KeyCode.Escape) && gamePaused == false){
gamePaused = true;
}
else if(Input.GetKeyDown(KeyCode.Escape) && gamePaused == true){
gamePaused = false;
}

if(gamePaused == true){
audio.Pause();
}

else if(gamePaused == false){
audio.Play();
}
}

Hope that works