- Home /
Sound on collision with rigidbody and rigidbody
I'm attempting to play a sound when two rigidbody collide, a ball hitting a cube. Do I attach the sound script to the ball? Do I attach the sound file to the ball too? and this is my code. I copied it from the forums and can't seem to get it working. Thanks for your help.
var body = other.rigidbody; var thump: AudioClip;
function OnCollisionEnter(collision : Collision) {
audio.Play(thump);
}
Answer by qJake · May 04, 2010 at 07:41 PM
That script is really incomplete. "audio" isn't defined anywhere, for starters.
If you want something to play on collision, attach an AudioSource to the object you want to make the sound. Load a sound clip into the audio source (all with the Inspector, no code yet). Then, attach something like this script to the same Game Object that you have your Audio Source attached to:
// C# public class CollisionAudioPlayer : MonoBehaviour { AudioSource asrc;
void Start()
{
asrc = GetComponent(typeof(AudioSource)) as AudioSource;
}
void OnCollisionEnter(Collision other)
{
if(asrc != null)
{
asrc.Play();
}
}
}
"audio" is a member of $$anonymous$$onoBehaviour and is a reference to this GameObjects AudioSource or "null" if no AudioSource is attached to this GO.
Thanks, updated my code. It's hard to remember what all the properties are without IntelliSense helping me. ;)
Thanks again for your help SpikeX and you to spree. I have a newb question. The actual sound file I want to play, call it "impact". I drag that onto the game object and do I mention it's name anywhere in this script? Like AUdioSource: impact; ? I'm also getting error CS8025: Parsing Error on line 6, which is the bracket under void Start for me.
What happens if you have two balls that collide to each other (instances). Each clone would have the same audio file and same script so do they play at the exact same time over each other? or would the audio files cut each other out or cause weird sounds?
Fixed my syntax error... somehow my parenthesis magically disappeared on me. You reference the sound file in your AudioSource component... go look on the Unity website under "Audio Components", all of this is explained in detail there.
Answer by rd42 · May 05, 2010 at 01:37 PM
Here's what I did and it worked. I attached the sound to the GO like you suggested, then out of the OnCollisionEnter documentation I used this,
function OnCollisionEnter(collision : Collision) {
// Play a sound based on size of impact.
if (collision.relativeVelocity.magnitude > 0)
audio.Play();
}
What I'm not sure of now is how to attach and reference multiple sounds to one game objects...
Your answer
Follow this Question
Related Questions
IPhone 4 and IPad 2 lost audio on resume 0 Answers
iPhone pitch not working? 1 Answer
Change Pitch on Collision 1 Answer
How to NOT play audio in silent mode with iOS? 1 Answer
How to avoid 'auto audio volume decrease' on iphone? 3 Answers