If I have multiple audio sources in an object then how do I set which sound effect I want to play at a specific time? Here’s the script I’m using:
public AudioSource[] sound;
public AudioSource sound1;
public AudioSource sound2;
void Start () {
sound = GetComponents<AudioSource>();
sound1 = sound [0];
sound2 = sound [1];
}
And to play the sound I use
sound1.Play ();
The strange part is that no matter how I set the array values, it keeps playing the sound2 audioclip instead of the sound1 one. Even stranger is that if I disable the sound2 audioclip, it doesn’t play anything. So what’s going on?
set the audio clips from the inspector where the script is attached to
public AudioClip audioClip1;
public AudioClip audioClip2;
public AudioClip audioClip3;
AudioSource myAudioSource1;
AudioSource myAudioSource2;
AudioSource myAudioSource3;
void Start()
{
myAudioSource1 = AddAudio (true, false, 0.2f);
myAudioSource2 = AddAudio (false, false, 0.3f);
myAudioSource3 = AddAudio (true, false, 0.4f);
StartPlayingSounds ();
}
public AudioSource AddAudio(bool loop, bool playAwake, float vol)
{
AudioSource newAudio = gameObject.AddComponent<AudioSource>();
//newAudio.clip = clip;
newAudio.loop = loop;
newAudio.playOnAwake = playAwake;
newAudio.volume = vol;
return newAudio;
}
void StartPlayingSounds()
{
myAudioSource1.clip = audioClip1;
myAudioSource1.Play ();
myAudioSource2.clip = audioClip2;
myAudioSource2.Play ();
//and so on
}
This is because the function GetComponents<> always works on top-to-bottom order if you really want to get control on the order of components then you must drag these sources in to inspector rather than getting them on runtime through code.
In your case change the order of sound2 this will behave oppositely. So my suggestion is not to use GetComponents<> if you don’t need this.