How to play music in Unity

I added some music to the PH test because I was tired of not having music.

Here is my pause script which switches the tracks playing. The Main Camera object has an AudioSource object (added when you drag and drop an audio file onto it).


using UnityEngine;
using System.Collections;

public class Pause : MonoBehaviour {
    bool paused = false;
    GameObject pauseCanvas, camera;
    AudioSource audioSource;
    public AudioClip pauseClip, musicClip;
    // Use this for initialization
    void Start () {
        pauseCanvas = GameObject.FindGameObjectWithTag("PauseCanvas");
        camera = GameObject.FindGameObjectWithTag("MainCamera");
        audioSource = camera.GetComponentInChildren<AudioSource>();
        pauseCanvas.SetActive(false);
    }
   
    // Update is called once per frame
    void Update () {
        if (Input.GetButtonDown("Cancel")) {
            paused = !paused;
            if (paused) {
                Time.timeScale = 0;
                Debug.Log("Paused");
                pauseCanvas.SetActive(true);
                audioSource.clip = pauseClip;
                audioSource.Play();
            }
            else {
                Time.timeScale = 1;
                Debug.Log("Unpaused");
                pauseCanvas.SetActive(false);
                audioSource.clip = musicClip;
                audioSource.Play();
            }
        }
    }
}

Comments

Popular Posts