How to play a specific sound from a gameobject with multiple sounds?

So basically my problem is how do I play a specific sound from a game object with multiple audio sources?

I looked through Unity’s Scripting API and at the moment I’m using this:

other.GetComponent<AudioSource>().Play();

The audiosource(s) are attached to the player.

However if I want to play a specific sound and I had say 2 audio sources attached to the player, how would I pick exactly which sound to play?

you could create public variables and drag them individually.

public AudioSource[ ] audio = new AudioSource[2];

then you could refer to audio[0] and audio[1] at will.

Thanks Fujik!
For some reason I can’t drag and drop the sounds into element 0 or 1 though? wierd?

If I wanted to play a clip what would the syntax be?

audio[1].Play();

My educated guess? :stuck_out_tongue:

Yeah, that would be it.

It makes sense that you can’t drag sounds into them as they are audiosources variables, meant to drag your audiosources into them, rather than your audio clips. You mentioned wanting to use 2 audiosources.

If you wanted to use a single audiosource, you could replace public AudioSource[] audio = new AudioSource[2]; with public AudioClip[] audio = new AudioClip[2];

Then, whenever you want to play a certain sound, you assign the proper audioclip to your audiosource so that it knows which clip to play, and then play it. Something like that:

GetComponent<AudioSource>().clip = audio[0];
GetComponent<AudioSource>().Play();
2 Likes

Oops, yeh, I didn’t mean audio source, I meant multiple audio clips, sorry for the confusion!
Thanks alot Fujik, this looks great, will get round to implementing it soon and I’ll let you know how I get on! :slight_smile: