2d Platformer not Working Right. Losing two Lives Instead of one

I changed my code because of what TheRaziel said. Now when I collide with a boulder I lose one life to turn it into 2, then when I hit the boulder again, my lives stay at 2. When I go under the platforms I lose a life to turn it into 2, then when I go under again, my lives turn to 1. Then when I go under a third time, my life stays at 1. Here is my project. It was made with Unity 2019.2.13f1 so you’re going to have to download that from the archive if u want to follow along.

   using System.Collections;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    public class DetectCollision : MonoBehaviour
    {
    int nbCoinsCollectedPerLevel;
    public static int score;
    public static int nbLives;
    
    // Start is called before the first frame update
    void Start()
    { 
    score = 0;
    nbLives = 3;
    nbCoinsCollectedPerLevel=0;    
    }
    // Update is called once per frame
    void Update()
    {
    }
    void OnCollisionEnter2D (Collision2D coll) 
     { 
     string tagName = coll.collider.gameObject.tag; 
     if (tagName == "pick_me") 
     { 
     Destroy(coll.collider.gameObject); 
    score++;
     nbCoinsCollectedPerLevel++; 
     if (SceneManager.GetActiveScene ().name == "level1" && 
    nbCoinsCollectedPerLevel >= 5) 
     { 
     SceneManager.LoadScene ("level2"); 
     } 
    print("score"+score); 
    } 
    if (tagName == "avoid_me" || tagName == "reStarter")
    {
    Destroy(coll.collider.gameObject); 
     nbLives--;
    Debug.Log("Collision in: " + coll.gameObject);  
     if (nbLives >= 0){ 
    SceneManager.LoadScene(SceneManager.GetActiveScene().name); 
    }
     else
    {
    SceneManager.LoadScene("lose"); 
    }
    
     print ("lives" + nbLives); 
    
    }
    /*if (tagName == "reStarter") 
    { 
     SceneManager.LoadScene(SceneManager.GetActiveScene().name); 
    }*/
    if (tagName == "endOfLevelTwo") 
    {
    SceneManager.LoadScene("win");
    }
     }
    }

Please help me.

Thanks

Hey!
I don’t have any experience with PlayerPrefs, however from what I understand, PlayerPrefs should be used for settings you wish to maintain between sessions, not for changing variables.

Try using public static variables instead, such as -

  public static int score;
  public static int nbLives;

    void Start()
    {
        score = 0;
        nbLives = 3;
    }

Then -

  • Attach this to a game object and use data persistence to maintain between scenes
  • Make sure to change this static variable directly (initGame.nbLives–:wink:

That should work but perhaps someone with more PlayerPrefs experience will be more helpful :slight_smile: