- Home /
Why will my audio not play in if statement?
I have looked around and cannot seem to find anyone with a similar problem, and I have tried many different ways to get my audio to play. I have a sphere that destroys when it is hit with another sphere using onCollisionEnter. That part works fine. Where i'm having issues is getting my audio clip to play when this happens. I have made one of the spheres an audio source, currently do not have the clip stored in the clip attribute of the audio source. I can get the clip to play by calling audio.PlayOneShot() in the Start() function, but not in my onCollisionEnter. Here is my C# code.
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "Dart") {
audio.PlayOneShot(Pop, 1f);
Destroy(collision.gameObject);
Destroy(gameObject);
}
Any help is greatly appreciated, Corey
Answer by amaceika · Dec 03, 2013 at 06:32 PM
You may want to destroy the object after you play the sound. So a simple solution would be a coroutine
IEnumerator Kill(float time)
{
yield return new WaitForSeconds(time);
Destroy(gameObject);
}
this is a simple sample. You can look at the reference page here.
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "Dart") {
audio.PlayOneShot(Pop, 1f);
Destroy(collision.gameObject);
StartCoroutine("Kill", 1f);
}
amaceika, I am still not getting a sound using your suggestion. I have used coroutines before, but I may not be doing something right. This is what I have now
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.tag == "Dart") {
audio.PlayOneShot(Pop, 2f);
Destroy(collision.gameObject);
StartCoroutine("$$anonymous$$ill", 2f);
//Destroy(gameObject);
}
if(collision.gameObject.tag == "Player") {
//Destroy(collision.gameObject);
Destroy(gameObject);
}
}
IEnumerator $$anonymous$$ill(float time) {
yield return new WaitForSeconds(2);
Destroy(gameObject);
}
Have I done something incorrect?
On which object does the clip exist? Because if it's on the collision object it will not play due to it being destroyed, if it is on the object that is in the Ienum it should technically work. I would also make sure that the play on start check box in the editor is off. If this doesn't work you may have to go about playing your sound differently like the other answer suggests. Write a class that all it does is play the sound clips based on when you need them to play. if it comes to that i can help yah write something quick.
Answer by thaiscorpion · Dec 03, 2013 at 05:52 PM
It won't play the audio because you are destroying the object before it plays. Try to play the audio from an object that won't be destroyed, like an audioController or something like that.