- Home /
why do I need to type variables classes?
Unity seems to work, wether I type float or boolean (for example) after class name or not.
Could you explain me why I need to type it?
Answer by dhendrix · Jun 22, 2010 at 11:43 PM
When using Javascript in Unity, you don't have to explicitly declare types. Such as:
var myInt = 5;
It's smart enough to know that you are declaring an int in this case. There are times when it can't figure out at compile time, so instead it has to figure out and typecast your variables at runtime, which can be costly in performance.
If you put "#pragma strict" at the top of your scripts, an error will be thrown if the type cannot be determined at compile time. Use this if you are worried about that little bit of extra performance.
for using the same variable name as me (before i even hit post! :P) and adding the pragma strict comment
Answer by Mike 3 · Jun 22, 2010 at 11:44 PM
Assuming you mean variable names:
Javascript's compiler has the ability to (most of the time) implicitly assign the right type to the variable
In those cases, you don't need to specify it
On the other hand, sometimes it can't, and it's forced to try guess the type at runtime
This can lead to some spectacular runtime exceptions, and even when it works, it's slower than typing it yourself.
The best practice is to type anything that isn't explicitly defined by the function or variable you're assigning to it
e.g.
var myInt = 0; //sets myInt to be an int
var myInt = FunctionThatReturnsAnIntExplicitly(); //sets myInt to be an int
generally you should never create objects like this:
var myInt;
It's asking for trouble
Type inference is not slower than explicit typing. No matter whether you specify the type or the compiler infers it, it results in the exact same thing and generates the exact same code. You may be confusing type inference with dynamic typing, but they are two very different concepts.
Not confusing it at all. I specifically said it happened when it couldn't infer the type
Oh, I see what "it" is referring to now. It seemed like you were referring to the implicit typing.