#pragma strict and GetComponent()

I am learning unity using tutorials. I learned the #pragma strict when using GetComponent generates this error:
Assets/scriptObjA.js(12,69): BCE0019: ‘foundVar’ is not a member of ‘UnityEngine.Component’.

MonoDevelop-unity adds the #pragma strict to my java script as default. is not used in the tutorials, is it a good practice to use it?

When I remove #pragma strict from the script, the code works correctly. Should I be concerned?
Is there a better technique to create/access global variable/functions?

I have parsed the code down from the tutorials down to this example:
The error is generated accessing a variable found in a script that is a component of a prefabsceneManager from an object called prefabObjA. Here are the two scripts:


scriptSceneManager.js


var foundVar : float = 20;

function Start () {
}

function Update () {
}

function FoundMe () {
}

scriptObjA.js


var varK 		: int = 3;
var lookFor 	: GameObject;

function Start () {

}

function Update () {
	print( lookFor.transform.GetComponent("scriptSceneManager").name );
	print( lookFor.transform.GetComponent("scriptSceneManager").foundVar );

}

I am assigning the variable lookFor in the interface with the prefabSceneManager that has scriptSceneManager.js as a component.
Thanks in advance for your help/advice.

You should use the typed version of GetComponent to avoid these errors: print( lookFor.transform.GetComponent(scriptSceneManager).name ); print( lookFor.transform.GetComponent(scriptSceneManager).foundVar ); The string version of GetComponent can find the specified type and its members at runtime, but is much slower - as @Eric5h5 said. It's better to use it only when the target script isn't available at compile time (when it's written in a different language, for instance).

–

1 Answer

1

Yes, you should use #pragma strict. It’s required when publishing to non-desktop platforms (iOS etc.) anyway, so if you intend to do that at some point, it’s best to be used to it. As for the actual problem, never use strings with GetComponent. It’s slower and makes GetComponent return Component instead of the actual type.

Please don't post comments as answers. :)

–

OK thanks for that clear up Eric. I tend to give a lot of erroneous information. :D However, I think that it's probably best at least for consistency and just in case there are some problems with #pragma strict, that people should use static typing wherever possible. Better safe than sorry?

–

As long as you supply a value, it won't ever cause problems with #pragma strict, and it is static typing. It can cause readability problems in some cases, such as when you get the return value of a function: var foo = SomeFunction(); It's not clear from that code what foo would be typed as; you'd have to look at SomeFunction to find out, so that's kind of bad.

–