Player stats resetting with constructor due to intialisation

Hi,

I am using a class to store my player stats, and was told one of the ways to achieve it is to use a constructor to create a new object. However, if I am assigning a new version of PlayerStats.cs each time with the constructor (in the code below), does that not then reset the PlayerStats.cs class too? (when main PlayerController.cs class reloads) as it requests a new version of it? (thus eliminating all of the the stored variables)

    void Start () {
        current = this;
        playerPhysics = GetComponent<PlayerPhysics> ();

        playerStats = new PlayerStats();
        Debug.Log ("Player stats score: "+playerStats.score);
        playerStats.getStats();
        Debug.Log ("Score after import:" + score);
     }

Here, my debug shows the score in PlayerStats.cs as the correct value, but in the code above, both before and after getStats(); is called, the value is 0. I tried setting the initialization value to 11 in PlayerController.cs, and the values are still 0, as if it is reading from a fresh copy of PlayerStats(); If I change the value of score in player stats to 11, it displays 11 in the game and correctly calls getStats() to set the value in PlayerController.cs to 11.

I don’t know whether I put the constructor in the wrong place, I probably did, but I can’t understand how it could work, if it keeps requesting a new version. (Calling getStats(); before the object is created creates another null exception ,which I understand is happening because the playerStats object hasn’t been created yet after the script reset.

How can I ensure that my stats in the separate class do not reset when the object call is made? Or have I completely misunderstood how objects work? :slight_smile:

Cheers

Lucio

I’m not sure what they were getting at, but if you do create a new object it will re-initialize. I use don’tdestroyonload, myself. I create an init scene, create the empty object and assign dontdestroyonload, then go to my working scene whatever that is. I use a public for the next scene so it’s easier to develop different scenes by changing the value in the editor. I’ve found there are different things I don’t want destroyed so an init scene is a good way to take care of it for me. It has to be a scene you won’t come back to, or it will cause duplication.

Typically for this I would use some static variables and functions. For example if getStats was a static function, you could call PlayerStats.getStats() without referencing a particular instance of the PlayerStats class.

Wow, I changed it all to statics and it passes the score perfectly to the file and back in again after resetting. Thank you so much :slight_smile: I’m sure I’ll run into some problems later but I can do so much until then :slight_smile: