Play Random Sound On FPC Collision With Wall

Hi guys, I'm looking for a script to put on the First Person Controller that plays a random sound from a selection of audio clips when the FPC collides with a surface tagged 'Wall'.

I managed to assemble an OnControllerColliderHit script that did this but the sound played continuously until the player moved away from the wall. Anybody got a script that would play the sound just once until the player moved away then collided with the wall again?

Any suggestions will be greatly appreciated. Many thanks, Will

You should use OnCollisionEnter instead of OnCollisionStay.

If that don't work you need to set a flag to prevent multiple activations e.g.

if(canPlay && hitWall){
   audio.Play();
   canPlay = false;
}

After an amount of time without touching the wall you can set can play to true again.

As for random sounds you can put all the sounds into an array and then call a random array item each time you hit a wall e.g.

var sounds : GameObject[];

function PlayRandomSound(){
  Instantiate(sounds[Random.Range(0,sounds.length)],transform.position,transform.rotation);
}

Depending on how you managed sounds

I have done something similar to this using OnCollisionEnter I believe. I had an array of AudioClips and I randomly picked on of the AudioClips and assigned it to a single AudioSource I had attached to my player. This way I could have all my settings set for my AudioSource (no looping, a set volume, 2D sound vs 3D sound, ect.) and I would just switch out the AudioClip and play the sound afterward.