- Home /
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!
Does the $$anonymous$$ouseClick script destroy the object? if it does then that would explain why it can't play a sound if the game object holding a reference to the source/audioclip is destroyed. Why not use WaitForSeconds to delay(by the length of the audio) the destroy if that is the case, play the clip, then let the destroy happen after?
Answer by AdamAz · Mar 20, 2015 at 02:16 PM
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.
Thank you! Indeed, the mouseClick script destroys the object. I just updated the Destroy command in that script with the parameter you gave me.
Thank you both!
Your answer
![](https://koobas.hobune.stream/wayback/20220613190658im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Trouble loading sounds into array 1 Answer
Play sound on mouse enter 1 Answer
Selecting and unselecting objects with raycast 2 Answers
Changing tagged objects in script 1 Answer