- Home /
Static Variables between Scenes
If I change a static variable in one scene will it remain changed when I load another scene?
for example if I use a script to change the variable
num from 1 to 2
then call on num in another scene will num be 1 or 2?
Answer by Statement · Jan 08, 2011 at 11:07 AM
Static variables remember their values across scenes. So, num will be 2 in the next scene in your example.
Example:
using UnityEngine; public class StaticExample : MonoBehaviour { public static int counter = 0; void Start() { Debug.Log(counter++); Invoke("ReloadLevel", 3); }
void ReloadLevel()
{
Application.LoadLevel(Application.loadedLevel);
}
}
0
UnityEngine.Debug:Log(Object)
StaticExample:Start() (at Assets/StaticExample.cs:7)
1
UnityEngine.Debug:Log(Object)
StaticExample:Start() (at Assets/StaticExample.cs:7)
2
UnityEngine.Debug:Log(Object)
StaticExample:Start() (at Assets/StaticExample.cs:7)
Awesome Answer! if I could vote it up twice I would :) very in depth and thanks man, I was planning on using static variables for getting stats between scenes and now that I see that it is possible I will be :)
In depth? :) I took the most shallow example I could think of (with added output so you dont need to run the program to see the results). There are many approaches for stats keeping in Unity Answers. Just search for them to see how people handle this issue. Ins$$anonymous$$d of using static variables you can also set some objects to not destroy on load.