r/UnityHelp • • Jul 31 '22

PROGRAMMING Losing 2 Lives Instead of 1 Please Help

My 2d platformer isn't working right. When I fall down under the platforms, I want to lose just one life. For some reason I always lose two. When I hit a boulder obstacle, I lose one life like I'm supposed to. Here's my project. It was made in Unity 2019.2.13f1 so you're going to have to download that from the archive if u want to follow along.

Please help me.

Thanks

3 Upvotes

2 comments sorted by

2

u/whitakr Aug 01 '22

Okay I pulled the project down and figured out what's going on. Your player has two colliders on it. But is moving so fast while falling that when they hit the restarter collider, both of its colliders end up getting the OnCollisionEnter2D callback, resulting in double results. All you need to do is add a simple bool that you set to true when they've already "died". This fixes the problem.

public class DetectCollision : MonoBehaviour
{
    int score, nbLives, nbCoinsCollectedPerLevel;

    // my 1st change starts here
    bool hitBottom;
    // my 1st change ends here

// ......
// ......
// ...... middle of your class
// ......
// ......

void OnCollisionEnter2D(Collision2D coll)
{
    string tagName = coll.collider.gameObject.tag;
    if (tagName == "pick_me")
    {
        Destroy(coll.collider.gameObject);
        score = PlayerPrefs.GetInt("score");
        score++;
        PlayerPrefs.SetInt("score", score);
        nbCoinsCollectedPerLevel++;
        if (SceneManager.GetActiveScene().name == "level1" && nbCoinsCollectedPerLevel >= 5)
        {
            SceneManager.LoadScene("level2");
        }

        print("score" + score);
    }

    // my 2nd change starts here
    if (!hitBottom && (tagName == "avoid_me" || tagName == "reStarter"))
    {
        hitBottom = true;
    // my 2nd change ends here

// ......
// ......
// ...... rest of your class
// ......
// ......

1

u/nstruth3 Aug 01 '22 edited Aug 02 '22

The code worked! Thanks a lot!