Integer only increases for a split second when "++" operator is used

Viewed 54

The integer gemsCollected does not increase its value when the NextLevel method is called.

The console shows that the value only becomes "1" for a split second. How do I make the script store the added value, instead of resetting it?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class gemTaken : MonoBehaviour
{
    public GameObject gem1;
    public Transform playerNearCheck01;
    public float playerCheckRadius01;
    public LayerMask playerLayer;
    private bool takenByPlayer; 
    public int gemsCollected;

    void Update()  
    {   
        Debug.Log(gemsCollected);
        takenByPlayer = Physics2D.OverlapCircle(playerNearCheck01.position, playerCheckRadius01, playerLayer);

        if (takenByPlayer)
        {
            NextLevel(); //calls method
            gemsCollected ++;
        }
    }

    void NextLevel() //method
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1 );
    }
}
1 Answers

if you declare the gemsCollected variable as "static", it will maintain it's value throughout scenes.

Furthermore, to keep it public you can make a getter method like this:

public int GetGemsCollected() => gemsCollected;

which is the same as this, if you're not familiar with the syntax:

public int GetGemsCollected() 
{
    return gemsCollected;
}

Then anytime you need the gemsCollected variable just call the method.

Let me know if that works.

Vlad

Related