Random audio time

Hello Lovely people could anyone suggest a way of scripting in an audio file so that it plays randomly as a piece of ambiance. e.g A helicopter traveling over the scene?

hmm, perhaps you could set the playing of that audio in a function.

In the start function, invoke it with a random time in seconds, and within the function, after it's played, invoke it again with another random wait (with a min / max you choose).

javascript example:

var soundToPlay : AudioSource;

function Start(){   

    Invoke("PlaySound", Random.Range(5.0, 20.0));

}

function PlaySound(){

    if (!soundToPlay.isPlaying)
        soundToPlay.Play();

    Invoke("PlaySound", Random.Range(5.0, 20.0));

}

EDIT in response to comments: In the above example, you drag a game object that has the desired audio source into soundToPlay in the inspector, or through scripting assign a GameObject.Audio component.

If the audio you're playing is on the same object as this script, you can do this:

var soundObject : GameObject;

function Start(){    

    Invoke("PlaySound", Random.Range(5.0, 20.0));
    if (!soundObject) soundObject = gameObject;

}

function PlaySound(){

    if (!soundObject.audio.isPlaying)
        soundObject.audio.Play();

    Invoke("PlaySound", Random.Range(5.0, 20.0));

}

as this just uses the game object's own audio source if you don't assign a different game object. This will allow you to script other game objects to be the sound object if you wanted to.

Thank you very very much!!