Death Counter Resets When Reloading Scene.

I’ve tried a number of things here, but I can’t seem to get the variables to stop resetting. I tried changing the integer to a static int, but it still reset. I also read that static variables should be avoided in most instances.

The script is attached to the player, and the death counter code I have is as follows:

    void OnTriggerEnter(Collider other) {

    if (other.gameObject.tag == "Dead") 
   	    {
		Application.LoadLevel (Application.loadedLevel);
		DeathCount++;
		SetDeathText ();
	    }
   }

If it helps in narrowing down the issue, as a test I also set the death counter to increase after a key is pushed, and the level to reset after a different one is pushed. The variables reset regardless.

Thank you.

Put this on the deathcount script on function awake:

DontDestroyOnLoad(transform.gameObject);

or you can set the deathCount variable as a playerPref: Unity - Scripting API: PlayerPrefs
so when you die:

PlayerPrefs.SetInt ("deathCount", PlayerPrefs.GetInt("deathCount") + 1); (untested)

And so, to display the score you would go with a PlayerPrefs.GetInt(“deathCount”);

Hi There! I’ve also heard a bit that static variables should be avoided but if you do decide to use it for your death counter I just tested your script with a static variable in JavaScript and it worked! Just a few small changes and you should be rolling! Goodluck.

static var DeathCount: int = 0;
var targetGuiText : GUIText;
    
    function OnTriggerEnter(other: Collider) {
    if (other.gameObject.tag == "Obstacle1"){
    Application.LoadLevel ("Level1");
    DeathCount++;
    SetDeathText ();
    }
    }
    
    function SetDeathText(){
    targetGuiText.text = "Deaths:" + DeathCount;
    }

I did find an answer if you still need it :smiley: