Collision Sound Not Working - My First Try - I've no idea how to do this!

I've started Unity programming a day ago with no prior knowledge of Java and pretty much zero knowledge of any kind of programming language. Right now I try to get a sound played on collision. I use exactly the following code + an audio source. Both appear in the inspector for the colliding object. I don't understand how this code works, so therefore I can't get it to work. For example, "audio.Play()" has nothing between the brackets, and I don't know if that's supposed to be like that. I don't see the connection between this code and the audio source, even though both appear in the inspector for this object. They don't share a common variable. I'm looking for a tip what do to to get the sound going + a tip what kind of book to buy to learn the basics of this, so I understand what I am doing, and I can actually start real coding instead of copying code and hoping it will work somehow.

function OnCollisionEnter(collision : Collision) { // Debug-draw all contact points and normals for (var contact : ContactPoint in collision.contacts) { Debug.DrawRay(contact.point, contact.normal, Color.white); }

// Play a sound if the coliding objects had a big impact.        
if (collision.relativeVelocity.magnitude > 1.1)
    audio.Play();

}

I've started Unity programming a day ago with no prior knowledge of Java

Java isn't supported in Unity.

As for your question, here's a few tips/questions:

  1. The 'audio' member field always refers to an AudioSource component, if there's one attached to the game object, or is null if there is no AudioSource component attached. In the case you describe, 'audio' refers to the AudioSource component you see in the inspector.

  2. Play() just starts playback on the referenced AudioSource component. Since all the parameters (audio clip, volume, pitch, etc.) are associated with the AudioSource component itself and can be modified via scripting or in the inspector, Play() doesn't need to take any arguments.

  3. Do you have a collider attached to the object?

  4. A quick way to debug the problem (or at least attempt to) would be to add some Debug.Log() statements to your OnCollisionEnter() function to determine a) if it's ever being called, and b) whether the conditional preceeding 'audio.Play()' ever evaluates to true. (The conditional checks the speed of impact, more or less, so if the objects aren't colliding at that speed or greater, the sound won't play.)

Thank you very much Jesse for the Debug.Log() tip.

I finally found the problem to be the missing audio listener. Now it works.