Don't change the variable value every time you load script

Hey there !

I’m new to unity and i’m trying to load scenes based on items collected.
Problem is that the counter is not counting my acquired items.
I’m using OnTriggerEnter2D() to trigger the event; Below is the snippet:

`private void OnTriggerEnter2D(Collider2D collision)
if (collision.gameObject.CompareTag(“Player”))
collectionNumber += 1;
if (collectionNumber == 1)
else if (collectionNumber == 2)
else if (collectionNumber == 3)
Debug.LogWarning(“All Items Collected !!”);

        cN.text = "Collection Number " + collectionNumber.ToString();

Whenever a new scene is loaded this script is loaded because it is on my quest item. And for every scene there is a quest item. So what I want to do is basically keep track of my collectionNumber, but it resets to 0.

Any help is much appreciated :slight_smile:

I think you have two different approaches to achieve this:

  1. You either write it to a file via some encoding - so players cannot modify the file easily - at the end of every scene and the start of every screen you read the file, decode it and store it in your variable. In long term you’ll have to do this anyways since if someone closes your application you’ll loose the variable unless you saved it somewhere outside of the program
  2. You make a class for e.g.: Globals, declare static variables and in its Awake or Start method you call the DontDestroyOnLoad() method on the GameObject itself. This method preserves your GameObject - and the attached scripts with its variables as well - even if a new scene is loaded. For more information, visit this link:

This is rather an old video but you can get the idea from here:

You could set the values on a game object that has dontdestroyonload() method, it could be your player or a game manager of some sort, it depends how you write your code, but if you exit the game the data will be lost. You can also save and load the data, here is a link to a good tutorial on that Preserving Data.