Question by
Sydneynumber9 · Oct 29, 2021 at 11:34 AM ·
c#unity 5vraudiosourceaudioclip
Play audio after enemy dies
Hello together, i have a issue that one audio is not playing, if the enemy is dead. Debug says it plays.
Here a little overview of my code:
public AudioClip deathAudio;
public AudioClip arrowhit;
private AudioSource audioSource;
*in Update session:*
audioSource = GetComponent<AudioSource>();
*than this:*
if (currentHealth <= 0)
{
audioSource.clip = deathAudio;
audioSource.Play();
..... destroy with delay
}
*and here if arrow hit (this works):*
if (collision.gameObject.tag == "projectile")
{
audioSource.clip = arrowhit;
audioSource.Play();
}
some have any idea?
2021-10-29-08-35-16-window.png
(35.9 kB)
Comment
Answer by rh_galaxy · Oct 31, 2021 at 10:42 PM
First you can have multiple audiosources. In the Init (Awake) method I get three.
AudioSource oASEngine; //set clip to engine in Inspector
AudioSource oASScrape; //set clip to scrape in Inspector
AudioSource oASGeneral; //set no clip in inspector
foreach (AudioSource aSource in GetComponents<AudioSource>())
{ //we have 3 audiosources
if (aSource.clip!=null && aSource.clip.name.Equals("engine"))
oASEngine = aSource; //engine sound is a looping sound that may play for a long time
else if (aSource.clip != null && aSource.clip.name.Equals("scratch"))
oASScrape = aSource; //scratch sound is a looping sound that may play for a long time
else
oASGeneral = aSource; //general audio source used for one shot audio
}
To play many clips overlapping each other you need to use PlayOneShot(), or the audio source will just change to the most recent clip assigned.
public AudioClip oClipExplosion; //drag here in inspector
public AudioClip oClipHit; //drag here in inspector
//on hit in Update()
if(bHit) oASGeneral.PlayOneShot(oClipHit);
if(bDead) oASGeneral.PlayOneShot(oClipExplosion);