0

I want the variable DC to increase by one every time EndGame is called, but, every time I die, It logs one instead of increasing each time.

bool gameHasEnded = false;
public float restartDelay = 1f;
int DC;


public void EndGame ()
{
    DC = DC + 1;
    Debug.Log(DC);

    if (gameHasEnded == false) 
    {

        gameHasEnded = true;

        Invoke("Restart", restartDelay);
    }        
}  
void Restart ()
{
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

}

Ruzihm
  • 19,749
  • 5
  • 36
  • 48
Linxs
  • 15
  • 5

1 Answers1

0

So the problem here is that DC is an instance variable. That means each time you create this script at run time (I.E. when loading a scene) that gets set to the default (here being 0).

Since your game ends every time you call EndGame, DC keeps getting reset. There are a few ways to go about fixing this.
The quickest is just to mark DC as static. This makes it a class variable rather than an instance variable and it will persist through scene changes.

Another thing you can do is mark this script as DontDestroyOnLoad. I consider this more dangerous as it can lead to having duplicated objects in subsequent scenes. It does exactly what it says, you just pass it the game object.

Other ways include scriptable objects and player prefs.
I'd recomend you try out static int DC; for this case. It's quick and simple.

Derek C.
  • 890
  • 8
  • 22