0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Think about what would happen to a game's menu music or UI navigation sounds if audio sources were forced to slow/stop when adjusting the gameplay time scale. \$\endgroup\$
    – DMGregory
    Commented Apr 4, 2019 at 8:57
  • \$\begingroup\$ Thanks, this is what I needed to understand \$\endgroup\$ Commented Apr 4, 2019 at 9:03

2 Answers 2

1
\$\begingroup\$

This isn't a bug. AudioSource will play independent of timescale. So you will need to reference your AudioSource and call .Pause() in your pause class.

\$\endgroup\$
0
\$\begingroup\$

You can use AudioListener.pause to true to pause them. and also you can specify some sounds sources to ignore that by setting AudioSource.ignoreListenerPause to true. Useful when you want some separate sounds to work while in pause menu.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .