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.
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.
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.