Unserialized private variable values from static instance persist when exiting play mode

In our scene, we have a static instance of a ‘GameInfo’ class that manages unserialized private values such as ‘volume’ and ‘score’. It is observed that while these variables are private, or unserialized, they will retain their values as they get set during editor play sessions instead of resetting to defaults, or ‘0’. If these values are made public, then they do reset to 0 between play sessions (which is what we want).

For example, the series of events would be something like:

  1. Enter play mode
  2. Acquire a score of 10
  3. Exit play mode
  4. Re-enter play mode
  5. Observe that the score is still ‘10’

Here is a snippet of our code:

namespace Assets.Scripts
{
    /// <summary>
    /// Singleton for high level game information
    /// </summary>
    [Serializable]
    public class GameInfo
    {
        private static GameInfo _instance;

        public static GameInfo Instance
        {
            get
            {
                if(_instance == null) _instance = new GameInfo();
                return _instance;
            }
        }

        private int _volume;
        private int _score;

[...]
     }
}

I can not reproduce what you say here. I tried all combinations of public / private and make the class serializable (as you did) / non serializable. In any case whenever i enter playmode the old singleton class instance is destroyed and a new one is created. static variables are reset when you enter playmode but are not reset when you leave playmode.

So if you see something to carry over from edit to playmode it has to be serialized somewhere in the scene or in an asset. Maybe you broke the golden rule of singletons? Never (ever) cache a reference to a singleton. Always use the global accessor, in your case your “Instance” property.

I adden a Debug.Log in the constructor of my singleton class as well as the finalizer (aka destructor) to see when an instance is created and when it is finalized (garbage collected). I also added a button to one of my test editor windows to print the current value of the private variable inside the singleton (accessed through a property).

So for me the singleton instance is destroyed / replaced when i enter playmode. So there’s no chance of anything can carry over.

Finally why would you actually put the Serializable attribute on a singleton class? You certainly don’t want any other system to create and initialize an instance of that class. Because that instance would not be stored in your instance variable. So if that’s really the behaviour you see, there has to be something else you did not mention.