- Home /
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();
}
Answer by Axtrainz · Nov 22, 2016 at 10:57 PM
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
Answer by Berawdu · Mar 13, 2014 at 08:52 PM
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.
Answer by samsut · Nov 22, 2016 at 08:48 PM
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.
Can be the Play(), it works too. In my project the Play() was restarting the music, then I found the UnPause() function and it worked. Now I tried in another project, and the play is working just fine.
Answer by oliver-jones · Apr 07, 2011 at 08:27 PM
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
I tried it but the audio keeps playing after I pause the game
in that case, you want to mute your Audio Listener, attached to your camera: AudioListener.volume = 0;
Your answer
Follow this Question
Related Questions
Different music for pause menu? 1 Answer
How would you make a Repeat-After-Me music game? 0 Answers
Audio keeps playing when paused 1 Answer
Problem with audio after leaving pause menu 1 Answer
AudioSource.Pause not working? 3 Answers