Search Unity

Static variable resetting on new scene load

Discussion in 'Scripting' started by Zaine7673, May 1, 2019.

  1. Zaine7673

    Zaine7673

    Joined:
    Feb 15, 2018
    Posts:
    238
    Hi,

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

    The holding class:
    Code (CSharp):
    1. public partial class myClass1
    2. {
    3.     public class Localisation
    4.     {
    5.         private static Dictionary<string, string> Text = new Dictionary<string, string>();
    6.  
    7.         public Dictionary<string, string> text
    8.         {
    9.             get
    10.             {
    11.                 return Text;
    12.             }
    13.         }
    14.     }
    15. }
    The calling class in Scene 2:
    Code (CSharp):
    1. public class myClass2 : MonoBehaviour
    2. {
    3.     private myClass1.Localisation localisation = new myClass1.Localisation();
    4.    
    5.     private void Start()
    6.     {
    7.         Debug.Log(localisation.text.Count);
    8.     }
    9. }
    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.
     
  2. Zaine7673

    Zaine7673

    Joined:
    Feb 15, 2018
    Posts:
    238
    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
     
  3. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    This is good case for lazy initialization pattern. You can do something like this:

    Code (CSharp):
    1. public partial class myClass1
    2. {
    3.     public class Localisation
    4.     {
    5.         private static Dictionary<string, string> Text = new Dictionary<string, string>();
    6.         public Dictionary<string, string> text
    7.         {
    8.             get
    9.             {
    10.                 if(Text.Count == 0) {
    11.                     initializeText();
    12.                 }
    13.                 return Text;
    14.             }
    15.         }
    16.     }
    17.  
    and have your dictionary initialized on demand, in any scene.
     
  4. Zaine7673

    Zaine7673

    Joined:
    Feb 15, 2018
    Posts:
    238

    Fantastic!! Why did i not think about this lol

    thank you this will help prevent further issues