Hi everyone,
I have sound on a health pickup that i want to trigger when I pick it up - so far I have this -
if (hit.collider.gameObject.tag == "health"){
hit.collider.gameObject.audio.Play();
healthScript.health += 20;
Destroy (hit.collider.gameObject);
}
Which works fine except for the sound. If i have “play on awake” ticked it plays when the game starts, which I dont want, but if i untick it, it wont play upon pickup. Am I going about this the wrong way?
Sorry for such a basic query, I must be missing something…
Cheers,
Will
You call Destroy on the game object playing the sound, which will also destroy the audio source, which in turn will stop playing. Thus no sound.
Oh i see… I had thought that if it was called before the Destroy it would play, then destroy the object… sorry for such a basic error. I’m still a bit fuzzy on the whole sound thing in unity - so how can I just call the sound… surely it has to be attached to something…
One solution is to first only disable the renderer of the object to be destroyed (so it disappears, but is not destroyed), then before the final Destroy() call yield WaitForSeconds() passing the length of the audio clip.
if (hit.collider.gameObject.tag == "health"
hit.collider.renderer.enabled
){
hit.collider.audio.Play();
hit.collider.renderer.enabled=false; // Stop rendering it
healthScript.health += 20;
// Wait for the audio to have finished
yield WaitForSeconds (hit.collider.audio.clip.length);
// Then Destroy
Destroy (hit.collider.gameObject);
}
Yes, that makes sense, thanks!
Another solution is to extract the sound clip and play it directly using AudioSource.PlayClipAtPoint:
if (hit.collider.gameObject.tag == "health" ){
var theClip = hit.collider.audio.clip;
var point = hit.collider.transform.position;
AudioSource.PlayClipAtPoint(theClip, point);
healthScript.health += 20;
Destroy (hit.collider.gameObject);
}