- Home /
Problems combining Audio triggers, PlayOneShot and Audio Arrays
I am having problems with audio triggers, Audio arrays and PlayOneShot. Ultimately I want to have an audio source with multiple audio clips that once a player walks through the trigger, will play a random clip from an audio array. However, once the random audio clip has played I don't want the audiosource to trigger again. I have a script for the PlayOneShot trigger, and another for the audio array. I want to combine the two or have two separate but functional scripts to do this.
The audio trigger script is as follows
var sounds : AudioClip;
private var hasPlayed = false;
function OnTriggerEnter(){
if(!hasPlayed) {
GetComponent.<AudioSource>().PlayOneShot(sounds);
hasPlayed = true;
}
}
and the audio array code is as follows (i have only two clips in at the moment)
var sounds : AudioClip[];
var LittleGirl : AudioSource;
var ManyWhispers : AudioSource;
LittleGirl.clip = sounds[Random.Range(0, sounds.length)];
LittleGirl.PlayOneShot;
ManyWhispers.clip = sounds[Random.Range(0, sounds.length)];
ManyWhispers.PlayOneShot;
Whether this is right or not I do not know since I am very knew to scripting. It seems that I cannot sue audio arrays and PlayOneShot and I cannot seem to combine the two scripts. Can someone please help me with a walkthrough of some kind. if there's any more information you need then please do ask!
Answer by tebandesade · Mar 18, 2015 at 06:22 PM
Hi! What about if you at the beginning define public var sounds : AudioClip[] an in the editor you just drag and drop the audios that you want to be included in the array. Afterwards when you're about to play the sound because of the trigger do something like int x = Random.Range (0, a.Length); and .PlayOneShot(sounds[x]);
Could be a solution! Could you give me that example in a code? I'm really not good at deciphering the order of where to put things in a script :(
var sounds: AudioClip[] ;
private var hasplayed = false ;
function OnTriggerEnter(){
if(!hasplayed)
{
var x = Random.Range (0, sounds.Length);
GetComponent.<AudioSource>().PlayOneShot(sounds[x]);
hasplayed = true;
}
}
Idk something like this maybe. And in Unity you have your audios and you'll se in the script component that a field size appear, you just modify that field for the amount of sounds you want and add them.