- Home /
play sound when collide?
hi does anyone know a script or can anyone make a script that plays a sound (1) time when the player collides
Answer by Rennat · Dec 01, 2010 at 05:46 PM
try this
var crashSound : AudioClip; // set this to your sound in the inspector
function OnCollisionEnter (collision : Collision) { // next line requires an AudioSource component on this gameobject audio.PlayOneShot(crashSound); }
http://unity3d.com/support/documentation/ScriptReference/AudioSource.PlayOneShot.html
Answer by oliver-jones · Dec 01, 2010 at 03:50 PM
Something like this:
function OnCollisionEnter(collision : Collision) {
if (collision)
audio.Play();
}
Not tested
I got most of this from the reference: http://unity3d.com/support/documentation/ScriptReference/Collider.OnCollisionEnter.html
i dont think that this script will work because it doesnt say what sound it will play or what tow object that has to collide
I'm guessing you want to make a noise on anything your player hits, so it should work. All you need to do is add a Sound Source and drag your sound file into it. (place the script on the graphic - where the collider is)
This works but not when object has "Is Trigger" checked. I would have upvoted you if I could. Thanks!
Answer by Mike 12 · Dec 01, 2010 at 11:03 PM
Here's my approach, for if you want to play more than one collision sound:
var thud:AudioClip; var ping:AudioClip;
function OnCollisionEnter(collision:Collision) { if (collision.collider.material.staticFriction == 0.25f) // This is how I decided to determine if a PhysicMaterial was metal audio.PlayOneShot(ping); else audio.PlayOneShot(thud); }
I haven't tested it out honestly, but I know that this should work. If you don't like what I used to determine if a collider's material was metal or not, then you could pick some other attribute of the metal PhysicMaterial that you think is unique.
Your answer
Follow this Question
Related Questions
Play An Audio Clip When An Instantiated Object Collides 1 Answer
Audio Playing upon death 1 Answer
How To play sound with a keypress 2 Answers
How to Play a Sound from an Array from an Overloaded Method? 1 Answer
Play a sound when flicker? 1 Answer