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. :)
collision.gameObject.CompareTag(“Ground”)
for better performance \$\endgroup\$