I am implementing pause game functionality in a Unity3D game using the following script
public class PauseGame : MonoBehaviour
{
/// <summary>
/// class to pause the game using Time.timeScale and
/// implement the related behaviours associated the game
/// </summary>
#region Fields
// Boolean variable that informs script if game should be paused or not, false by default.
private bool isPaused = false;
#endregion
#region MonoBehaviour Messages
/* ----------------------------------------
* At Start,
*
*/
void Start()
{
}
/* ----------------------------------------
* Whenever 'ESC' key is pressed, toggle 'isPaused' boolean
* and call SetPause() to pause/resume game
*/
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
isPaused = !isPaused;
SetPause();
}
}
#endregion
#region Methods
/* ----------------------------------------
* A function to pause/resume the game
*/
public void SetPause()
{
Debug.Log("SetPause");
// Invert 'isPaused' boolean and convert it into a float variable, being true = 1; and false = 0f.
float timeScale = !isPaused ? 1f : 0f;
// Set the Time Scale as 1(game runs normally) or 0(game pauses)
Time.timeScale = timeScale;
}
#endregion
}
All the game elements pause as expected using the above, except the background music. I can pause the background music by additionally referencing the AudioSource and disabling it while timescale is set to 0. However, I was wondering whether it was a bug. Kindly suggest.