Unity – Audio EFX – OnClick – GetKey

1. Put a Sphere in the Scene

2. MAIN TOP MENU> Assets> Import New Assets> load a file.mp3

3. Projects> Assets> DRAG AND DROP file.mp3 over the Sphere
NOTICE: you have to put the mp3 in the scene or it does not play! WE NEED ABSOLUTELY AN AUDIO SOURCE!

4. Create a script audioplay.js> DRAG AND DROP audioplay.js over the Sphere
NOTICE: assign the js at the same object that has the mp3 file

5. The Script:

#pragma strict

function Start () {

}

var audioplay : AudioClip;
function OnMouseDown ()
{
        // When you click over the object
        audio.PlayOneShot(audioplay, 0.7);
}

function Update () {

}

6. Select the Sphere> Inspector> Audio Source> Uncheck ‘Play On Awake’ or it plays at first frame when the game stars.

7. Select the Sphere> Inspector> audioplay.js> Audioplay> click small circle icon and assign the file.mp3

DONE!!!

Change the script to GetKey and start audioplay:

#pragma strict

function Start () {

}

var audioplay : AudioClip;

function Update () {

 // You have to use - GetKeyDown - because return TRUE only in the first frame.
 // If you use - GetKey - return multiple TRUE throught frames and audio restarts every frame!
 if (Input.GetKeyDown("up")) 
 audio.PlayOneShot(audioplay, 0.7);

}