Hi,
I have a folder under my Resources folder called audio in which I have stored a number of audio files. I’m trying to write a script which, when triggered, will play one of these files at random. My script doesn’t give any compile errors, but it doesn’t work. Could someone please show me where I’ve gone wrong?
var isPlaying : boolean = false;
var thisSound : AudioSource;
var sound : AudioClip;
var myClips : AudioClip[] = Resources.LoadAll("audio/webb", AudioClip);
function OnTriggerEnter(){
if(isPlaying == false){
isPlaying = true;
sound = myClips[Random.Range(0, myClips.Length)];
audio.PlayOneShot(sound);
}
}
function OnTriggerExit(){
if(isPlaying == true){
isPlaying = false;
thisSound.Stop();
}
}
The AudioSource remains a component from where I was using a single audio file specified in the inspector (which I had working), but I’m not sure whether I need it or not with this method.
Thanks in advance.
I’m not sure what the problem is, but I can think of a few things to try. First, it looks like you are messing with 2 separate audio sources. In OnTriggerEnter you say “audio.PlayOneShot” and in OnTriggerExit you say “thisSound.Stop”.
The other thing I noticed is that Resources.LoadAll returns an Object array. Even in their JS example code they load the resources into an Object array. I’m not sure if this is a problem, but you might try changing your myClips array into an Object array like they have in their example code.
Hi, and thanks for the pointers (I’m very new to this system). I’ve rationalised how the audio is handled a bit (just using audio.Play() and audio.Stop() for instance), but the script is still seemingly not getting the audio from the folder. It runs ok, and some other texture related parts work, and the audio works for a single file (in the inspector), but I get an error to the console when trying to read the folder:
Object reference not set to an instance of an object
which I take it to mean that
var myClips : Object[] = Resources.LoadAll("audio/webb", AudioClip);
is not actually loading anything in to the array.
Any ideas please?
Ok, I have it working now. I wasn’t doing the Resources.LoadAll(…) inside a running function, in my case Start(). I moved that line into the start function, but had to declare the Object[ ] at the top of the script. After that it worked. Now looks like this:
//
// play a random sound from a folder
//
var isPlaying : boolean = false;
var thisSound : AudioSource;
var myClips : Object[];
function Start(){
myClips = Resources.LoadAll("audio/webb",AudioClip);
}
function OnTriggerEnter(){
if(isPlaying == false){
isPlaying = true;
audio.clip = myClips[Random.Range(0, myClips.Length)];
audio.Play();
}
}
function OnTriggerExit(){
if(isPlaying == true){
isPlaying = false;
audio.Stop();
}
}