Play sound when clicking object

Good day friends,

I’m trying to write some simple code (in JS/Unity 4) to play a sound clip when I click on an object. Generally, when I click an object, I destroy the object via another script. However, before I destroy the object (or at the “same time”), I want to play a sound clip.

Here is my code for playing a sound clip:

#pragma strict

var SoundEffect : AudioSource;

function Start () {

}

function Update () {

}

function OnMouseClick(){

	gameObject.audio.Play();
}

I have imported a sound clip, added it to my Hierarchy, dragged the above script onto a cube object, and dragged the sound clip (as an audio source) onto the script component.

I tried different ways to code the sound, but I can’t seem to figure it out. What am I missing? Is there a different way to code the sound? To confirm, the sound plays when I set the Sound Source (PUNCH) to “Play on Wake”.

Thank you!

Hi,

you can either use WaitForSeconds as suggested by Landern or use the Destroy method with it’s second parameter destroy doc for example:

Destroy(gameObject, audioClip.length);

Personally I prefer the destroy approach since it dose the same and is much less code.