Static variable resetting on new scene load

Hi,

I cant seem to figure out why a static variable is resetting when a new scene is loaded.

The holding class:

public partial class myClass1
{
    public class Localisation
    {
        private static Dictionary<string, string> Text = new Dictionary<string, string>();

        public Dictionary<string, string> text
        {
            get
            {
                return Text;
            }
        }
    }
}

The calling class in Scene 2:

public class myClass2 : MonoBehaviour
{
    private myClass1.Localisation localisation = new myClass1.Localisation();
   
    private void Start()
    {
        Debug.Log(localisation.text.Count);
    }
}

On Scene 1, the dictionary is populated and has a count of 83. Everything is fine in scene 1. However when Scene 2 is loaded the count is 0.

I’m using static variables on this project and do not have this issue with any other. the code looks simple enough and i cant figure out where its resetting. probably something so simple.

I’m happy to post the full scripts if needed.

How do i delete this thread???

OMG this is so embarassing lol

So for those who are interested - the issue was that i was running scene 2 in the editor directly. so the dictionary was never populated as that happens in scene 1. So to make it work i had to run scene 1 and then change to scene 2 from within the game.

of course, it all makes sense now LOL

This is good case for lazy initialization pattern. You can do something like this:

public partial class myClass1
{
    public class Localisation
    {
        private static Dictionary<string, string> Text = new Dictionary<string, string>();
        public Dictionary<string, string> text
        {
            get
            {
                if(Text.Count == 0) {
                    initializeText();
                }
                return Text;
            }
        }
    }

and have your dictionary initialized on demand, in any scene.

Fantastic!! Why did i not think about this lol

thank you this will help prevent further issues