# How do I play a sound after a given time is over?

I have a sound effect in my game that I want to play every time there is a collision detected, the problem is that the collisions are very frequent and the sound plays many times and gets overlapped, which doesn't sound good.

The code is simple enough, I just put a walkSound.Play() in the OnCollisionEnter method.

I also tried using a coroutine but I don't get the desired result:

private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
StartCoroutine(WalkSound());
}

}

IEnumerator WalkSound()
{
walkSound.Play();
yield return new WaitForSeconds(0.41f);
}


The WaitForSeconds could be above the playing code, but then there is an unnecessary delay that I don't need.

Basically what I want to achieve is, to have code execute the Play() method only when the previous iteration of the sound reaches 0.41f seconds. This is similar to having an if statement that checks if the sound is already playing, but I want the sound to overlap at a given time.

Hope I was clear enough, any help appreciated. :)

• Side note: use collision.gameObject.CompareTag(“Ground”) for better performance Jul 1 '20 at 13:28
• Thanks for the tip! Jul 2 '20 at 8:24

One way to do it is to keep track of a state variable, like so:

private bool soundReady;
private void OnCollisionEnter(Collision collision)
{
if (soundReady && collision.gameObject.tag == "Ground")
{
StartCoroutine(WalkSound());
}

}

IEnumerator WalkSound()
{
walkSound.Play();
yield return new WaitForSeconds(0.41f);

When you want to avoid playing the sound while it is already playing, you can check the property AudioSource.isPlaying and only play the sound when it isn't already playing.