- Home /
Collide sound
I hope it is very simple.I have a an object and when it is thrown down to the floor i want a sound to be played(just for the collision,like"boop").So,i have the sound clip and i've made an audio source on the floor,in which i put the clip.How can i connect the collision with the sound ?I can't think of a script..
Answer by aldonaletto · May 26, 2011 at 05:34 PM
You could use the OnCollisionEnter event to trigger the sound, like this:
function OnCollisionEnter(coll: Collision){
GetComponent<AudioSource>().Play();
}
The audio source and this script should be assigned to the floor object (it works with the terrain too). Remember to uncheck Play On Awake in the audio source, or you will hear the sound every time the game starts. Set also the Doppler Level to 0, or the sound may become unrecognizable when you're moving fast. Finally: the object which will fall to the ground must have a rigidbody to trigger the event.
NOTE: This answer was updated to Unity 5 by replacing the audio "variable" with the code GetComponent<AudioSource>() (which previous versions of Unity called behind the scenes anyway).
Thank you very much.You solved my problem and gave me some extra info ! :D
Please mark aldonetto's answer as the correct answer for your question so other's know your question has been resolved.
Any drawback on assigning this script to the throwed object ins$$anonymous$$d?
No trouble, as long as the script and the AudioSource both are part of the same object. The only difference is: if attached to the moving object, the sound will move with it. Not a big deal for short sounds, but may make a difference for longer ones. NOTE: the 'audio' variable has been removed in more recent Unity 5 versions, thus I've replaced it with the more correct GetComponent() code (which older versions called behind the scenes anyway).
Answer by DaveA · May 26, 2011 at 04:59 PM
This should give you some hints: http://unity3d.com/support/documentation/ScriptReference/Collider.OnCollisionEnter.html
http://unity3d.com/support/documentation/ScriptReference/AudioSource.Play.html
Your answer
Follow this Question
Related Questions
Collider + multiple sounds script 1 Answer
Audio Loops? 1 Answer
When is audio file loaded to memory 0 Answers
Only able to play a single sound through AudioSource. 1 Answer