Friday, October 25, 2013

Unity Sound Example - Looping, Random Sound Files for Triggered Event

A quick demo that makes use of AudioClip[], audio.loop, audio.isPlaying, update(), and a true / false flag in order to play back a looping array of randomised sounds when an event trigger is activated.

In this example, a single sound source that loops is replaced with an array of sound assets that are randomly played back for every loop.

This example uses the unity 4.x demo "Angrybots". The standard autofire gunshot sound - which loops continuously when the fire button is held down - is replaced with an array of sounds (which could be slightly varied gunshot sounds) and change with every loop.

In short, the process for this particular example is:
• Find an in-game object that currently triggers a single sound that loops continuously
• Find the script that is associated with that object that triggers that sound
• Add an AudioClip[] array variable to the top of the code e.g.:
var RandomSoundNames : AudioClip[];
• Find the function within that script
• Add code above that reads:
audio.clip = RandomSoundNames[Random.Range(0, RandomSoundNames.length)];
audio.loop = false;

• Find or create the update() { } function in the same script
• Add the following code to the update() function:
if(autofire == true && audio.isPlaying == false) {
audio.clip = RandomSoundNames[Random.Range(0, RandomSoundNames.length)];;

• Remember to inspect the object in Unity via the Inspector and update the random audio array with audio assets!