- Home /
How can I stop sound continuously playing on Collision?
I am making a game a game where you shoot to move. My player bounces and I have made it so that whenever he touches the ground, a bounce sound effect plays. But the script is registering a lot of bounces, hence playing the sound effect multiple times, which I do not want. How can I make it so that once he touches the ground, the sound effect only plays once, and doesn't register again when he is on the ground.
Note: sound effect looping is turned off.
Here is my code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerSoundEffects : MonoBehaviour { public AudioSource bounceSoundEffect;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Obstacles"))
{
bounceSoundEffect.Play();
}
else
{
bounceSoundEffect.Stop();
}
}
}
Answer by prakyathd801 · Dec 29, 2020 at 08:34 AM
You can use bool variable to handle the states
private bool isSoundPlayed = false;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.CompareTag("Obstacles"))
{
if(isSoundPlayed = false)
{
bounceSoundEffect.Play();
isSoundPlayed = true;
}
}
else
bounceSoundEffect.Stop();
}
Your answer
Follow this Question
Related Questions
public variable audio clip not initializing sound 0 Answers
Why can't my character jump 2 Answers
character jump on collision with a box 0 Answers
OnCollisionEnter Sine Wave to Character 0 Answers
Getting errors after destroying objects and playing sound? 0 Answers