- Home /
Sound on collision not working
Hi, i am using this script:
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);
}
OK, so what i did is when my Player (tagged as player) collides with this object which is a sphere is should create a sound. Sound does not get played i tried searching form many scripts but still no luck out here. I did put an audio source to my sphere and audio listener to the camera and also tries attaching this script to my player as-well but sound doesn't get played. This script was found in other question.
The first thing you should do it to make sure that OnCollisionEnter is called. Please, add a Debug.Log().
Answer by aldonaletto · Oct 09, 2012 at 11:59 AM
If your player is a CharacterController (like the First Person Controller prefab, for instance), this won't work: collisions rigidbody->characterController generate OnCollision events in the rigidbody script, but collisions characterController->rigidbody don't.
Collisions follow some schizophrenic rules - specially when a character controller is colliding with something else. The usual collision event associated to character controllers is OnControllerColliderHit, but the event is generated only in the CC script - and it happens all the time due to collisions CC->ground.
If the only purpose is to generate a sound when the player hits the sphere, you could make the sphere collider a trigger (check Is Trigger in the Inspector) and use OnTriggerEnter:
var crashSound : AudioClip; // set this to your sound in the inspector
function OnTriggerEnter (other: Collider) {
// next line requires an AudioSource component on this gameobject
audio.PlayOneShot(crashSound);
}
The only problem here is that the CC could pass through the sphere, since triggers are "transparent" from the collision point of view. A simple solution would be to create another sphere a little smaller and place it at the same position: the CC would be detected by the bigger trigger, but could not pass through the smaller collider.
NOTE: The CC must penetrate the trigger deep enough to be detected, thus the trigger must be about 0.2 to 0.4 units larger than the internal collider.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Stop another sound from another script? 1 Answer
How to play Audio Once if enemy has enterd a trigger 1 Answer
How to loop a sound clip on a ButtonDown function 1 Answer
Need help making an audio trigger. 2 Answers