- Home /
Sound plays multiple times after StartCoroutine when it should only play once.
I've made a power up to my Breakout styled game where you get 200 points instead of 100 points when you hit a break for 10 seconds. I created an IEnumerator which yield returns a WaitForSeconds(10f) and plays a "Ding" sound when it ends. Then, I added a StartCoroutine in OnCollisionEnter2D because that is the function which destroys the bricks and calculates the points. However, while the power up works as it should, the "Ding" sound plays multiple times when it should only play once. I am new to IEnumerators and Coroutines and so I can't really tackle this problem by my own. I would love it if you helped me, thank you.
void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.tag == "brick")
{
ad.PlayOneShot(breakBrick);
int num = Random.Range(0, 10);
if (num == 9)
{
Instantiate(extra, collider.gameObject.transform.position, collider.gameObject.transform.rotation);
}
if ((num == 7 || num == 8) && !isX2)
{
Instantiate(x2, collider.gameObject.transform.position, collider.gameObject.transform.rotation);
}
Destroy(collider.gameObject);
if (isX2)
{
StopCoroutine(X2());
StartCoroutine(X2());
points = points + 200;
}
else
{
points = points + 100;
}
numBroken++;
}
}
IEnumerator X2()
{
yield return new WaitForSeconds(10f);
ad.PlayOneShot();
isX2 = false;
}
Hello @sharonv , it's possible that you have more than one X2 object and hit twice o more of then? In this case, you will have multiple "X2()" execution because using "StopCoroutine" only work on its gameObject.. if you have multiple instance, it can't work on others..
try checking if the sound is already playing before you play it.