- Home /
Audio effect on collision
Hi. I have two objects, a player and an enemy, and I have the following script attached to the enemy (as well as the sound effect).
void OnCollisionEnter2D(Collision2D coll){
if (coll.gameObject.tag == "Player"){
audio.Play();
}
else {
audio.Stop();
}
}
I want when the player hits the enemy, this sound effect to be played, but in my case the effect is played at the begining of the scene.
How can i fix this?
Answer by Saad_Khawaja · Jul 17, 2014 at 12:31 PM
There is nothing wrong with the script although you don't need to do audio.Stop(); in the else part.
If the audio is playing at the beginning then you've probably checked Play on Awake of the audio source. Uncheck "Play On Awake" in the inspector window for the GameObject on which you have added the audio source.
Have you assigned an audio clip to it? Also, can you log into the collission function to see if that function is called:
Debug.Log("colliding")
Can you remove the audio.Stop(); line and try again?
Answer by HarshadK · Jul 17, 2014 at 12:32 PM
Looks like you have Play on Awake on your audio source file checked. You need to uncheck it.
For more info: Audio Source
Your answer
![](https://koobas.hobune.stream/wayback/20220613154318im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Photon help for a noob! 0 Answers
I want there to only be 5 objects on screen at any time, can someone help please? 2 Answers