Playing Sounds in Unity

Keenan Gray
1 / 7

Unity supports a range of sound files[wav,mp3,etc]

I downloaded several ".wav" files from freesound.org, but you can also record your own sounds using your phone.  You should also install Audacity, an easy to use sound editing program.   

Start by dragging and dropping the sounds into a folder in the editor.


Code to place in "update script" assigned to the gameobject with the audiosource

  if (Input.GetKeyDown(KeyCode.Alpha0))
        {
            GetComponent<AudioSource>().Stop();
            GetComponent<AudioSource>().Play();
        }


If you want multiple game objects to play sounds you can assign this script to each, with a few modifications

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Play : MonoBehaviour
{
    public KeyCode key;  
    // Start is called before the first frame update
    void Start()
    {
       
    }
    // Update is called once per frame
    void Update()
    {
          if (Input.GetKeyDown(key))
        {
            GetComponent<AudioSource>().Stop();
            GetComponent<AudioSource>().Play();
        }
    }
}

Then assign the key in the editor, as seen in the images above