I have a bunch of creatures that comes in a swarm, and each of them have the same audio clip which is them making noises.
So when I let them go, they all play the clip at the very start which makes it very loud and unrealistic. Is there a way to pick a random point in the clip so it gets all distributed?
Rather than picking a random point in the clip you can delay the start of the clip. The easiest way to do this is to make sure the each objects AudioSource does not have “Play On Awake” enabled and delay the start of the clip through your script. Below is an example of how to assign a random delay to each creature starting to play the clip:
JavaScript Example:
#pragma strict
// Make sure there is an AudioSource
// attached to this object
@script RequireComponent(AudioSource)
// The minimum and maximum delay
// value in seconds
var minDelay : float = 0.0;
var maxDelay : float = 5.0;
function Start ()
{
// Just to make sure we are
// going to disable the play
// on awake for the AudioSource
audio.playOnAwake = false;
// Make sure there is an
// AudioClip to play before
// continuing
if(audio.clip)
{
var delayTime : float = Random.Range(minDelay, maxDelay);
audio.PlayDelayed(delayTime);
}
}
C# Example:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class DelayAudio : MonoBehaviour
{
public float minDelay = 0.0f;
public float maxDelay = 5.0f;
void Start ()
{
// Just to make sure we are
// going to disable the play
// on awake for the AudioSource
audio.playOnAwake = false;
// Make sure there is an
// AudioClip to play before
// continuing
if(audio.clip != null)
{
// Get a random number between
// our min and max delays
float delayTime = Random.Range(minDelay, maxDelay);
// Play the audio with a delay
audio.PlayDelayed(delayTime);
}
}
}
The scripts above have a maximum delay of 5 seconds by default, but you can easily change that to suit your needs.
EDIT: Corrected conditional check for audio clip in C# code to make it check for null reference.