- Home /
Caching global vareiables? (n00b question)
Does Unity cache global variables between test plays? I notice that when I create a global variable (Outside of any function/method) and initialize it in the same line as the declaration, run the game, then change it and run the game again, the new value doesn't take effect. (I do stop the test play before I edit it and save, so it's not like I do this while the game is running) Is this intended behavior? If so, how do I make it recognize the change?
I know using global variables is bad coding practice, I'm going through a tutorial that has code that uses them. Just want to understand why the engine is acting the way it is.
To duplicate:
var num : int = 7;
function Update () { Debug.Log(num); }
Unity version: 3.3.0f4
OS: Windows 7
Thank you!
Answer by Waz · Jul 04, 2011 at 09:58 PM
There are no global variables. What you are seeing is variables visible in the Inspector being saved. If you don't want this for a variable, mark it private or NonSerialized. See this question.
Are there any side-effects to doing that? $$anonymous$$eaning, will it affect anything else other then make the variable not visible/editable from the Inspector GUI?
private will make them inaccessible to other classes (good if you want to keep your code maintainable).
So if I want it accessable to other classes, the only place I can change the initial values of the script-level variable is in the Inspector and not script itself?
If you mark it NonSerialized, it will not be in the inspector, but other classes will be able to access it. What exactly do you want to happen?
A script Foo.JS is actually a class Foo that extends $$anonymous$$onoBevaiour. It's magically wrapped for you by Unity. They are not "script-level", simply class instance variables.