How to pick which component you want?

I wish to have a UI element play three different sounds.

  1. Slide in
  2. Slide out
  3. Click

I can add 3 AudioSource components to the game object but how do I specify which of the components I wish to play? Is there an easy way to play differnet sounds without having to create multiple empty game objects attached to the UI?[/i]

Yup. Create an array of AudioClips (AudioClip[ ]), put the three sounds into it in the inspector, and then set the AudioSource.clip to the AudioClip in the array you want to play.

Just be sure to use AudioSource.Stop() before you switch the clip, just in case. The clip won’t switch if it’s currently playing.

Thanks for the help while this worked.

I had it working great until I had to change the size of the array to add more sounds. Now I get an Index out of Range error on any new sounds. I tried resetting Unity even and still get the errors. I also tried changing the variable name to no avail. And, as a kicker, once I deleted the var and created a brand new one every new audio clip array tells me index out of range…

I’d check your script, then. If it says index out of range, then that means you called an index out of range, most likely.

I did.

I have var mySounds AudioClip[ ];

At first I set the size in the Inspector to 5 and selected 5 audio clips.

When I called audio.PlayOneShot(mySounds[0]) everything worked great up to calling [4].

Then, I went into the Inspector and changed the size to 8. I selected three more audio clips.

I changed my code to call audio.PlayOneShot(mySounds[5]); and it bombs with the IndexOutOfRange error.

When I comment out the code I don’t get the error. If I call audio.PlayOneShot(mySounds[4]) it works just fine, acting like its still a size 5 array. I tried creating a brand new array of AudioClips and now I get an error calling even audio.PlayOneShot(myNewSounds[0]) with a size of 20. Also, when I changed my var back to mySounds[ ] it recognized it as a size of 8 again. Does it cache this stuff somewhere?

Any ideas on what I’m doing wrong would be helpful. :slight_smile: