Sound FX playing twice at end of level

I observed in my implementation that sometimes, the win SFX were playing twice, sometimes even before the final enemy died. It took a bit of sleuthing, but I think I figured out what’s going wrong and how to fix it. I’m surprised The Full Rick solution didn’t fall afoul of this same problem.

I’ve provided the ‘solution’ code below, and the comments hopefully articulate what the problem was.

Any thoughts welcome. Was I the only person who experienced this? I did depart from the lecture code in a couple of places during the Challenges…

 public void AttackerKilled()
    {
        numberOfAttackers--;
        StartCoroutine(CheckEndLevel());  //was originally just a normal method, I made it a coroutine
            
    }


   IEnumerator CheckEndLevel()
    {
        //the problem is the end level function only calls on kill. this can take place during a spawn delay
        //that means there cases when, temporarily, there are zero enemies but one is coming soon (because of spawn delay)
        //so it can happen that timer is finished, zero enemies left, triggering the win SFX, but actually it's too early to celebrate!
       //solution is to put a delay equal to the spawn delay before ending 

        if (FindObjectOfType<GameTimer>().TimerFinished())
        {
            StopSpawners(); //we still need to do this when time runs out.
            Debug.Log("spawners are off, but some enemies may be on the way!");
            yield return new WaitForSeconds(FindObjectOfType<EnemySpawner>().getSpawnDelay()); //won't necessarily get the LONGEST delay
            if (numberOfAttackers <= 0) //this can still get triggered more than once so not perfect 
            {
                Debug.Log("End the level now!");
                StartCoroutine(HandleWinCondition());
            }
        }
    }
1 Like

Thank you for posting the solution :blush:

Privacy & Terms