Value should increment, not toggle between two int's after OnTriggerEnter

Hello guys,

I have a problem with incrementing. I’m a beginner at coding, but you will see.
If I Trigger the Function I get both the values 0 and 1 back for the variable "
checkpointCounter"
… what’s the problem?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CheckpointSystem : MonoBehaviour
{
    public int checkpointNumber;
    int checkpointCounter;
    public Text lapsText;
    int laps;


    void Start()
    {
        laps = 0;
        checkpointCounter = 0;
    }

    private void Update() {
        Debug.Log(checkpointCounter);
    }

    void OnTriggerEnter2D(Collider2D carOverCheckpoint){
        if(carOverCheckpoint.gameObject.name == "Car")

            if(checkpointNumber == 1 && checkpointCounter == 0)
                checkpointCounter++;
            else if(checkpointNumber == 2 && checkpointCounter == 1)
                checkpointCounter++;
            else if(checkpointNumber == 3 && checkpointCounter == 2)
                checkpointCounter++;
            else if(checkpointNumber == 4 && checkpointCounter == 3)
                checkpointCounter++;
            else if (checkpointNumber == 5 && checkpointCounter == 4){
                laps++;
                lapsText.text = "Laps: " + laps;
                checkpointCounter = 0;
                }
    }
}

Thanks for your help.

I’m assuming you have several CheckpointSystem scripts in your scene. As it stands, if you have even just 2 objects with this script on it, when the game starts, they both print out 0 in the console. When you hit the first one, that one should print 1 and the second one prints 0.

There isn’t anything here that has the two share the value of checkpointCounter.

Either checkpointCounter has to be static, or, a better system may be to have a central script that manages all the checkpoints and the other script handle the checkpoint trigger and talk to the main script.

1 Like

alright, this helped me a lot, thank you.
Your more efficient suggestion might be something for a future project… :smile: