How To Pause Music?

Updated on August 11, 2017 in General
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
4 on August 11, 2017

Hey, Guys! I’m making a space exploration game. In my “Main Menu” scene, I have a GameObject that has an Audio Source (my music), and a script that has a DoNotDestroyOnLoad function in it.

Here is the script:

 

 

  1. using UnityEngine;
  2. using System.Collections;
  3. public class DontDestroy : MonoBehaviour {
  4. void Awake ()
  5. {
  6. GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
  7. if (objs.Length > 1)
  8. Destroy(this.gameObject);
  9. DontDestroyOnLoad(this.gameObject);
  10. }
  11. }

I could not for the LIFE of me, figure out how to pause and unpause this music via my pause menu, which was in a completely different scene, called “Space.” Is there anything I could put into the following script to fix this.

 

  1. using System.Collections;
  2. using UnityEngine;
  3. public class PauseGame : MonoBehaviour {
  4. public Transform canvas;
  5. public GameObject player;
  6. // Update is called once per frame
  7. void Update () {
  8. if (Input.GetKeyDown (KeyCode.Escape))
  9. {
  10. if(canvas.gameObject.activeInHierarchy ==false)
  11. {
  12. player.GetComponent<PlayerMovement> ().enabled = false;
  13. canvas.gameObject.SetActive (true);
  14. } else
  15. {
  16. player.GetComponent<PlayerMovement> ().enabled = true;
  17. canvas.gameObject.SetActive (false);
  18. }
  19. }
  20. }
  21. }

 

Thank You for you help anyone.

  • Liked by
Reply
0 on August 11, 2017

https://docs.unity3d.com/ScriptReference/AudioSource.Pause.html

  • Liked by
Reply
Cancel
1 on August 11, 2017

I tried this, I wasn’t successful. Then I tried the mute function, which I believe to be more useful. 

here is what I added to the PauseGame Script:

public AudioSource audioSource<span style="color: #333333;”>;

 

void Start ( )  {
        audioSource <span style="color: #333333;”>=
<span style=”color: #333333;”> GetComponent<AudioSource>();
          }

    void Update () {

        if (Input.GetKeyDown(KeyCode.M))
            audioSource.mute <span style="color: #333333;”>=<span style=”color: #333333;”> !audioSource.mute<span style="color: #333333;”>;

 

Guru
on August 11, 2017

However, muting isn’t pausing meaning that when you resume the game your music continues at a different point than where you wanted to pause it.

Show more replies
  • Liked by
Reply
Cancel
0 on August 11, 2017

You can disable/enable the audio source component and i think it should work like a pause, dont know if it’s good practice though

  • Liked by
Reply
Cancel