pragma strict

I’m trying to understand pragma strict but I’m a bit confused. I thought it will report compile errors when I don’t define the type and disable dynamic typing. But why do I not get any errors in this code…

#pragma strict
var lol;
function Awake()
{
	lol = 45+5;
	lol = "wtf";
}

With #pragma strict, you will get errors in this code:

function Blah (varA, varB) {

You will also get errors in this code:

GetComponent("SomeScript").SomeFunction();

However, it’s true that the code you posted will compile and run (slowly). Personally I’d consider that a bug, and that #pragma strict shouldn’t allow it to compile.

Unity dynamic typing still can pick up on basic variables such as integers and strings. Pragma strict really comes in handy when you’re casting anything that is in direct correlation with the Unity framework, such as a GameObject versus a Transform.

From the docs:

  1. Use #pragma strict

Now the problem is of course, that you
don’t usually notice when you are
using dynamic typing. #pragma strict
to the rescue! Simply add #pragma
strict at the top of a script and
Unity will disable dynamic typing in
that script, forcing you to use static
typing. Wherever a type is not known,
Unity will report compile errors. So
in this case, foo will produce an
error when compiling:

Now in regards to you first using it as an integer and then using it as a string, I’m going to assume that Unity’s implementation of javascript is dynamically changing the type on the fly as well. Although Unity’s js is extremely fast because of the way they designed it and is probably easier to use than c#, I still prefer c# because of syntax and much stricter casting parameters as to prevent any possible mishaps like this in your code.

So, like I said, I can only assume that it’s recasting the variable on the fly for you as to not error out.

Use #pragma script at the top of your scripts when Javascripting