Trouble with multiple audiosources

Just a quick one - the code Ben gives in this one will cause exceptions if you have your callsound as the second audiosource component on the prefab. It also may not play your recorded callsound. I believe this is because the code will pick the first audiosource with the call to GetComponent.

To fix the problem just move the callsound AudioSource above the rotor sound in the hierarchy (will break the prefab so re prefab it). I’m sure theres a code way to do it too :smiley:

1 Like

Using code, I just managed to do it with a bit dirty trick, using the AudioClip’s name

void Start () {
		foreach(AudioSource audio in GetComponents<AudioSource> ())
		{
			if (audio.clip.name != "helicopter") {	
				call = audio;
			}
		}
	}

just another quick question related to this… could you in code get components for both audio sources and if so how could the code decipher between the two?

Hi @Veronica_Zemenovich,

You could use GetComponents<AudioSource>() to get the 2 AudioSources.

Then, you SHOULD be able to use the Inspector Component Order to find which AudioSource is the one you want (SLIGHTLY MOAR DETAIL: https://answers.unity.com/questions/1293957/reliable-order-of-components-using-getcomponents.html - BE CAREFUL using this method on all but the most updated versions).

Failing that, you could use the properties of the different AudioSources to distinguish them (is there a clip? if so, what name? what’s the volume? Spatial Blend (2D, 3D, mix between)?..)

Hope this helps