Sound volume based on rigidbody velocity before collision.

I found this, but as to using that in an if-statement, I have no idea. Here's me poorly attempting to come up with a snippet of code that might be a part of what I need to do:

var Hitsound : AudioClip;

function OnCollision (collision : Collision) {
        if (collision.relativeVelocity.magnitude > 0.5) {
                ???
       }
}

What I'm basically trying to do is to have the sound volume directly match the velocity of the rigidbody before it collides, so it sounds more natural. I could really use some help with this.

This is very old. I’m trying to solve this problem too, but anyway the code above has an initial problem:
volume must be a value between 0 and 1, where 0 is 0% of the volume of the clip and 1 is 100%. So if you do audio.volume = collision.relativeVelocity.magnitude; this will fail because the velocity magnitude can be greater than 0. You can use Mathf.Clamp01 but if most of the times velocity on collisions is higher than 1, all those collisions will have volume = 1 so you will notice no difference in a collision with velocity = 2 and velocity = 20. If velocity on impact is random (the object can vary a lot its own velocity) you must get a max value (aprox) and divide by it. For example if most of hits are in the range of 5 - 20 velocity, you can do:

audio.volume = Mathf.Clamp01(collision.relativeVelocity.magnitude / 20);

off the top of my head something like this…it doesnt work but it might help put you in the right direction (hopefully)

EDIT: Fixed ambiguous reference, still will crash unity though

//unstable, will crash Unity

@script RequireComponent (AudioSource)

var collide : AudioClip[]; //array of audio clips

var audioVolume : float; //volume

var audioLength : float = 1; //length

function OnCollisionEnter(collision : Collision) { //on collision

audio.clip = collide[Random.Range(0, audioLength )]; //random audio clip from array
        
audio.volume = collision.relativeVelocity.magnitude; //set volume to speed of object

audio.Play(); //audio play

}

This works ideal for your case

hitsound.volume= rb.velocity.sqrMagnitude / 100;

Tweak the values to your liking,