Pause sounds and background music in Unity

507 views Asked by At

I am making a Pause menu in Unity that appears when you press escape. But whenever I press escape, the background music still plays. I am getting an error in lines 32 and 46. The error log is Assets\PauseMenu.cs(32,32): error CS0029: Cannot implicitly convert type 'UnityEngine.AudioSource' to 'UnityEngine.AudioSource[]'

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PauseMenu : MonoBehaviour
{
    public static bool GameIsPaused = false;
    public GameObject pauseMenuUI;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            if (GameIsPaused)
            {
                Resume();
            }
            else
            {
                Pause();
            }
        }
    }

    void Resume()
    {
        pauseMenuUI.SetActive(false);
        Time.timeScale = 1f;
        GameIsPaused = false;

        AudioSource[] audios = FindObjectOfType<AudioSource>();

        foreach (AudioSource a in audios)
        {
            a.Play();
        }
    }

    void Pause()
    {
        pauseMenuUI.SetActive(true);
        Time.timeScale = 0f;
        GameIsPaused = true;

        AudioSource[] audios = FindObjectOfType<AudioSource>();

        foreach (AudioSource a in audios)
        {
            a.Pause();
        }
    }
}
1

There are 1 answers

0
Art Zolina III On BEST ANSWER

FindObjectOfType<AudioSource>() return only one object to return an array of object use FindObjectsOfType<AudioSource>()