Adding sounds



Playing sounds at random intervals

This is really useful for ambient sounds, such as ducks, rats, people, traffic, etc.

Clink on this link to download some rat sounds to add to your project

Tutorial video

The code
//This script has been adapted from a script found at the site below: // // I added the multiple sounds and the random intervals. // Repeatedly play a sound with a given fixed time interval between // the sound events. var sound1 : AudioClip; var sound2 : AudioClip; var sound3 : AudioClip; var sound4 : AudioClip; // AudioClip to be played var minTime : float; var maxTime : float; private var nextTime: float; private var sounds: Array; // Time interval in seconds between sound events private var currentTime : float; private var timeInterval: float; function Start() { nextTime = 0; } function Update () { // Check if it is time for the next sound event currentTime = Time.time; if ( currentTime >= nextTime ) { choice = Random.Range(0, 4); if( choice == 1){ sound = sound1;} else if ( choice == 2) { sound = sound2;} else if ( choice ==3) { sound = sound3;} else { sound = sound4;} GetComponent.<AudioSource>().PlayOneShot(sound); timeInterval = Random.Range(minTime, maxTime); nextTime = nextTime + timeInterval; //print("Time "+ Time.time); } }
Introduction and download

Proximity based sounds are sound that are activated when you come within a certain distance of an object. They are super easy to do, you just need a trigger!

Before you move on to the video you should download the sheep bleating sound from the link below!

Tutorial Video
var sound : AudioClip; //This gives us the option to select an mp3 file in the properties pane function OnTriggerEnter () { //This is the function that is fired when another object collides with this one. GetComponent.<AudioSource>().PlayOneShot(sound); // This is how we play the sound. We could do other stuff here instead. }