I am looking to set up a selection of audio clips to play at random on, for example, a footstep collision with the ground. There is very limited documentation on this but it is a MUST in game audio. I am only a sound designer but my programmers seem to find this quite hard. I’m guessing I would have to set up some kind of array and randomly select from it.
Could anyone give me an example of some script to do this.
N.B I will want to randomise the pitch and volume too if possible so if you could include this in the script I would be most most grateful!
Thanks!
Hi,
maybe this sample code will help you:
#pragma strict
public var stepSounds : AudioClip[];
...
function PlayRandomSound() {
if (stepSounds.length>0) {
var idx : int = Random.Range(0,stepSounds.length-1);
audio.clip = stepSounds[idx];
audio.pitch = Random.Range(0.9, 1.1);
audio.Play();
}
}
Keep in mind that if the audio clips length is larger than the footstep interval that the audio clips may be stopped. You could use this function to play more than one audio clip at the same time :
function CreateSound(aclip : AudioClip, rolloff : float, volume : float, pos : Vector3, multiPlay : boolean) {
if(!aclip)
return;
if(!multiPlay) {
if( GameObject.Find("/" + createSoundPrefix + aclip.name) || GameObject.Find("/" + createSoundPrefix + aclip.name + "(clone)") )
return;
}
var sound : GameObject = new GameObject();
sound.transform.position = pos;
sound.name = createSoundPrefix + aclip.name;
sound.AddComponent("AudioSource");
sound.audio.clip = aclip;
sound.audio.rolloffFactor = rolloff;
sound.audio.volume = volume;
sound.audio.Play();
// destroy gameobject after the audioclip has been player
Destroy(sound, sound.audio.clip.length+0.5);
}
Wow thanks! And would I attach those scripts to the players foot and have the “Collisionsoundeffect” or the “Foot” script reference them? Do you know how I would do this?
You can use/define AnimationEvents in the script that controls the animation. You have to define one AnimationEvent for each animation frame/time when a foot touches the ground. See the documentation for further details.
Another thing most people do is randomly vary the pitch (and sometimes volume as well, depending on the terrain surface) of a footstep clip within a small range, so that the same audio clips sound slightly different each time – this will let you cut down on the number of physical audio files needed in the game, which will reduce footprint (audio is large). This is especially important for iPhone games but is also relevant for web games; it is less relevant for standalone downloaded games. A simple line such as myAudioSource.pitch = Random.Range(minPitch, maxPitch) will do it.
Cheers,
psn
Necro - does any kind of builtin randomisation exist like this 10 years later in Unity Mixer/Audio? I know its a standard feature in FMOD, but I need to transition back to Unity Audio due to the problems that FMOD causes on some portable devices.