DE: Programming In Unity

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

Intro to Unity Programming

Keenan Gray

The world's of Unity are made up of individual pieces called "GameObjects". Each game object has a collection of components that dictate its behavior. Using programming (scripting) these behaviors can be expanded and manipulated.


In the example script we are manipulating a property on the rigidbody. We are applying a force based on keyboard input.

more information about rigidbody https://docs.unity3d.com/ScriptReference/Rigidbody.html


more information about input

https://docs.unity3d.com/ScriptReference/Input.html

Freesound files

Keenan Gray
20018__djfroyd__1-16-groovy-beat-and-stems.zip