- Home /
Problems playing multiple Audio Sources in prefabs
Wonder if someone could help me. I'm having an issue plying multiple audio sources on my enemy tank prefabs .
I have added two audio sources (which play just fine elsewhere in the game). I then attach my two audio source components to my script component (below). However, only the first sound will play.
public AudioSource hitAudioClip;
public AudioSource deathAudioClip;
Start ()
{
AudioSource[] audioSources = GetComponents<AudioSource>();
hitAudioClip = audioSources[0];
deathAudioClip = audioSources[1];
}
TakeDamage()
{
hitAudioClip.Play ();
}
EnemyDeath()
{
deathAudioClip.Play ();
}
I've read a few posts which point at doing it just like this, but I just cant get it to play the second sound. I'm beginning to think it might be some sort of unity bug..?
Am I doing something wrong?
Thanks in advance, Dave
It should work however it is not a better way to do the same (You should use only one AudioSource component and use some AudioHandler Script to handle which audio is played).
It is not unity bug it should work, you may be doing some wrong like
You are using same audio clip for both AudioSources
TakeDamage() is getting invoked when actually EnemyDeath() should be invoked
Let me know if it helps
Hi @amanpu,
Thanks for your reply to my question.
I definitely have different audio sources:
And they're both referenced in my script:
Also, EnemyDeath invokes an explosion and then destroys the gameobject (after playing the explosion sound clip, of course) and this is working, so I know EnemyDeath is being called.
I only hear the hit sound though, regardless of their order in the inspector. Note: it does this with any combination of sources, so I know it's not the audio files either.
you have already defined the audio sources as public, so just drag drop in inspector and call the "TakeDamage" & "EnemyDeath", accordingly.
There is no need to use it as GetComponent.
This doesn't work either, which lead me to try the GetComponents method.
To be clear, if I remove/comment-out these lines in start():
//AudioSource[] audioSources = GetComponents<AudioSource>();
//hitAudioClip = audioSources[0];
//deathAudioClip = audioSources[1];
I don't get either sound played. Could it be something wrong with Unity 5.2?
public AudioSource hitAudioClip; public AudioSource deathAudioClip;
// void Start () // { // AudioSource[] audioSources = GetComponents(); // hitAudioClip = audioSources[0]; // deathAudioClip = audioSources[1]; // }
void Update()
{
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.T))
{
TakeDamage();
}
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.E))
{
EnemyDeath();
}
}
void TakeDamage()
{
hitAudioClip.Play ();
}
void EnemyDeath()
{
deathAudioClip.Play ();
}
Answer by MadDevil · Sep 28, 2015 at 06:14 AM
why are you using GetComponet ?
Just drag the audiosource into the public variables, you have defined, assign the clip to individual audiosource and you will be able to play both of them.