- Home /
Pause Menu Audio
he guys. i have a pause menu c# script and i want it to stop the audio in the background when it pauses. here's the script:
using UnityEngine; using System.Collections;
public class PauseMenu : MonoBehaviour { public GUISkin myskin;
private Rect windowRect;
private bool paused = false , waited = true;
private void Start()
{
windowRect = new Rect(Screen.width / 2 - 100 , Screen.height / 2 - 100, 200, 200);
}
private void waiting()
{
waited = true;
}
private void Update ()
{
if (waited)
if(Input.GetKey(KeyCode.P) || Input.GetKey(KeyCode.Escape))
{
if (paused)
paused = false;
else
paused = true;
waited = false;
Invoke("waiting",0.3f);
}
if(paused)
Time.timeScale = 0;
else
Time.timeScale = 1;
}
private void OnGUI()
{
if (paused)
windowRect = GUI.Window(0,windowRect, windowFunc, "Game Paused");
}
private void windowFunc(int id)
{
if(GUILayout.Button("Resume"))
{
paused = false;
}
if(GUILayout.Button("Options"))
{
}
if(GUILayout.Button("Return to Main Menu"))
{
Application.LoadLevel ("Main Menu");
}
}
}
Any suggestions? Thanks!
Where is the audio? Just tell it to http://unity3d.com/support/documentation/ScriptReference/AudioSource.Stop.html>Stop() when you pause the game, when you resume tell it to Play() again. There are some other things do in addition, like saving the playback position(time or timeSamples) before stopping the clip, then you can play at that specific position when you resume the game(good when changing scenes). Otherwise you can use Pause().
Answer by Berenger · Jun 03, 2012 at 04:33 PM
Call Pause on your audioSource when you pause the game, Play when you unpause. The way you handle your booleans is redundant, here is a better way :
private void Update ()
{
if (waited)
{
if(Input.GetKey(KeyCode.P) || Input.GetKey(KeyCode.Escape))
{
paused = !paused;
if( paused ){
Time.timeScale = 0;
audio.Pause();
}
else{
Time.timeScale = 1;
audio.Play();
}
waited = false;
Invoke("waiting",0.3f);
}
}
}
Your answer
Follow this Question
Related Questions
Audio keeps playing when paused 1 Answer
Pause Menu 3 Answers
Paused Menu backdrop 1 Answer
how to pause and resume music after pausing game? 4 Answers
Pause Menu Problems 2 Answers