- Home /
2 audio sources on a game object, how use script to instruct one to play?
If I have an empty game object with two audio sources, each with a unique audio clip.
How, in script, do I pick one from the other? Let's say one audio source has a audio clip called jump.mp3 and the other has grunt.mp3
is it something like
var grunt : Audio Source; grunt = audio source with grunt.mp3
And then use grunt to talk to that one?
Or is there a way that a script attached to the game object with the two audio sources can directly talk to a chosen audio source without having to assign a variable?
Answer by Statement · Mar 13, 2011 at 10:40 PM
You can define two different audio sources as public variables and bind them in editor. Just drag the component into the variable slot in the inspector.
var audio1 : AudioSource;
var audio2 : AudioSource;
When you then want to play either of those you can call
audio1.Play();
// or
audio2.Play();
Or if you want you can use GetComponents(AudioSource); to get an array of them, and you can enumerate through them. I think the first solution is easier though.
I searched for solutions for 2-audiosource-in-one-object problem and this answer came up. Expanding upon Statement's javascript solution, here's how you do an array in C#:
public AudioSource[] sounds;
public AudioSource noise1;
public AudioSource noise2;
Then in Start()
sounds = GetComponents<AudioSource>();
noise1 = sounds[0];
noise2 = sounds[1];
And then it's whichever sound you want to play:
noise1.Play();
noise2.Play();
Since I wanted to alternate between sounds on collision, I created a bool variable & made a function that would play noise1 when the bool == true and noise2 when false.
how do you know which AudioSource component is assigned to which array element? Does GetComponents grab the components in top-down order?
Answer by efge · Mar 13, 2011 at 10:11 PM
I think you do not have to use multiple AudioSources on one GameObject. From the reference for AudioSource: Multiple sounds can be played on one AudioSource using PlayOneShot.
You could assign your audio clip to a variable (or an array) and use for single events like shots etc.:
var grunt : Audio Source;
audio.PlayOneShot(grunt);
or if you want more control of the AudioClip:
audio.clip = grunt;
audio.Play();
I think you still need multiple AudioSources if you need to start and stop clips independently. Once you play a clip with PlayOneShot, I don't think it can be stopped.
For game music and sound effects (some of which need to loop), I'm using at least 2 AudioSources.
Answer by adriana · Dec 19, 2011 at 10:53 PM
Just a simple question: if I have two AudioSources, can they play together their two different audios ???
In code: if I write
audio1.Play();
audio2.Play();
can all of them play their sound, or only will play audio2 ???
Tnx !!
Do not ask a question in an answer. Start your own new question