Unity C# Coroutine not functioning properly

88 Views Asked by At

I have a coroutine that is used to track time and score. Every 10 seconds, the score is updated and a sound is played, and every 6 seconds, there is another sound. When the time goes to 0 game ends. This part is working fine. Problem is in the area that I have highlighted.

On a collision with checkpoint, I want to increment the time by 5 seconds and play a sound but the time is not incrementing on collision and the sound is not played. To debug, I added the Debug.log("Collided") line to make sure that collision is occurred, and the console shows collided when the collision occurs so there is no problem with the collision.

This is my checkpoint trigger code:

private void OnTriggerEnter(Collider other)
{
    print("Hit checkpoint");
    PlayerPrefs.SetInt("CheckPointHit", 1);
    gameObject.SetActive(false);
}

Code for the coroutine

    IEnumerator LoseTime()
    {
        while (true)
        {
            yield return new WaitForSeconds(1);
            currentTime--;

            if (currentTime % 10 == 0)
            {
                currentScore -= SCORE_INCREMENT;
                GameObject.FindGameObjectWithTag("MainCamera").GetComponent<AudioSource>().PlayOneShot(scoreSound);
            }
            if (currentTime % 6 == 0)
            {
                GameObject.FindGameObjectWithTag("MainCamera").GetComponent<AudioSource>().PlayOneShot(explosionSound);
            }

            if (PlayerPrefs.HasKey("CheckPointHit"))
            {
                if (PlayerPrefs.GetInt("CheckPointHit") == 1)
                {
                    currentTime += TIME_INCREMENT;
                    GameObject.FindGameObjectWithTag("MainCamera").GetComponent<AudioSource>().PlayOneShot(checkpointSound);
                    PlayerPrefs.SetInt("CheckPointHit", 0);
                    Debug.Log("Collided");
                    Debug.Log(currentTime);
                }
            }

            if (currentTime <= 0)
                break;

            if (gameEnd == true)
                break;
        }

        GameOver();
    }

On a collision with checkpoint, I want to increment the time by 5 seconds and play a sound but the time is not incrementing on collision and the sound is not played.

Update: As per the debug statement, Debug.Log(currentTime);, it seems that the time is incrementing but it not incrementing in the display.

The function to display is below and I am calling it in Update():

private void UpdateLabels()
{
    tmScore.text = "Score: " + currentScore;
    tmTimeLeft.text = "Time Left: " + currentTime; 
}
1

There are 1 best solutions below

0
KiynL On

This method of your coding is very heavy. Keep in mind that the GameObject.Find and GetComponent functions are among the heaviest and should be avoided when there is no need for them.

private Camera camera; // cached Camera
void Start()
{
    camera = Camera.main;
    //...
}

Before playing the sound, make sure that the AudioListener and AudioSource are set correctly. For testing, it is better to test on 2D.

2D

And then it's enough to write the following code, if the error is not resolved when running Debug.Log, the sound problem is not from your code.

[SerializeField] private AudioSource audioSource;
...

audioSource.PlayOneShot(soundClip); // better way to play sounds..