Error in tutor's code (or bug in Unity?) - Coin AddToScore not adding up correctly

[Solved] S14: L345: Error in tutor’s code (or bug in Unity?) - Coin AddToScore not adding up correctly. Help!

You can see the error at video time 12m25s - 12m35s - coin score goes 100, 200, 300, 500, 600 (skips 400) - there are only 5 coins! - I too have had this error in my score: I initially set pointsForCoinPickup = 1; in CoinPickup.cs and it goes 1, 2, 4, 5, but I also tried with 100 and it still produces this error.

Is it a bug in Unity? Or something not right in code? Can’t get it to add up the score properly, no matter what I try fiddling with in code.

Solution: Thanks to Nina in your udemy course Q&A: “Please add a Debug.Log to see how often the method that adds coins get called. It might be that it gets called too often.”
– It was indeed getting called twice on some coin interactions.

"In this case, add a bool and an if statement in your CoinPickup script. For example:

    bool isCollected = false;    
 
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(isCollected) { return; }
 
        isCollected = true;        
        FindObjectOfType<GameSession>().AddToScore(pointsForCoinPickup);
        AudioSource.PlayClipAtPoint(coinPickUpSFX, Camera.main.transform.position);
        Destroy(gameObject);
    }

"
This solved it.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms