If I say:
var someVariable = 1;
This is creating a variable called someVariable.
But what if I didn’t have the “var”
someVariable = 1;
is that creating a variable called someVariable too? What’s the difference between the two?
If I say:
var someVariable = 1;
This is creating a variable called someVariable.
But what if I didn’t have the “var”
someVariable = 1;
is that creating a variable called someVariable too? What’s the difference between the two?
Using “var” is part of the script. Unity can’t understarnd what you did.
If you say var life = 1.2;
THEN it will create a variable.
But life = 1.2; will be discarded.
Does this answer your question? ![]()
The keyword var makes declaration of local variables (new variables inside a function) explicit. If you don’t use it, Unity will assume that the first instance of a new word in a function is a new local variable. You don’t need it for local variables, but it is very useful for making your code legible, as it should mark the first appearance of a variable in a function. Using var means there’s always an easy answer to the question “where did this variable come from?”
You always need to use var outside functions in order to declare global variables (such as ones visible in the inspector).
Another thing you can’t do is declare the same thing twice:
var newVariable = 1;
var newVariable = 2;
newVariable = 1;
var newVariable = 2;
In the second example, the variable was declared implicitly (without the keyword “var”), so the second mention cannot attempt to declare it. The following will work, however:
var newVariable = 1;
newVariable = 2;
newVariable = 1;
newVariable = 2;
Note that each time, the new variable is declared first (implicitly or explicitly), and then referenced without var in order to assign it a new value.
This is incorrect. Try the following script:
function Start() {
newVariable = 10;
Debug.Log(newVariable);
}
It will write the number 10 to the log without complaining.
Thanks for clarifying it Muriac.
You should know that this is specific JS. In C# (and for the most part, the whole C-family of language) there are different keywords for declaring variables as different types and in different scopes.
Some languages you don’t need any keywords. For example, in Lua you can just create a variable anytime, anywhere just by creating a name and setting it equal to some value.