Harsh patel
Harsh patel

Reputation: 475

Keeping variable from changing on another scene load

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;
        Destroy(gameObject);
        if (collectionNumber == 1)
        {
            collision.gameObject.transform.Find("Acquired_Items").GetChild(0).gameObject.SetActive(true); 
            qiCollector.gameObject.transform.GetChild(0).gameObject.SetActive(true);
        }
        else if (collectionNumber == 2)
        {
            collision.gameObject.transform.Find("Acquired_Items").GetChild(1).gameObject.SetActive(true);
            qiCollector.gameObject.transform.GetChild(1).gameObject.SetActive(true);
        }
        else if (collectionNumber == 3)
        {
            collision.gameObject.transform.Find("Acquired_Items").GetChild(2).gameObject.SetActive(true);
            qiCollector.gameObject.transform.GetChild(2).gameObject.SetActive(true);
        }
        else
        {
            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 :)

Upvotes: 0

Views: 42

Answers (1)

Menyus777
Menyus777

Reputation: 7037

First method: Don't allow your object to be destroyed on scene load https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

public static void DontDestroyOnLoad(Object target);

Above code will prevent destroying your GameObject and its components from getting destroyed when loading a new scene, thus your script values

Second Method: Write out your only value into a player pref https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

// How to save the value
PlayerPrefs.SetInt("CollectionNumber", collectionNumber);
// How to get that value
collectionNumber = PlayerPrefs.GetInt("CollectionNumber", 0);

Third method: Implement a saving mechanism: In your case i would not suggest this

Upvotes: 1

Related Questions