pragma strict scripting problem

here is my script

#pragma strict
var target : Transform;
if (target.GetComponent(BallScript))
{
            target.GetComponent(BallScript).GoHome(); 
}

this script works correctly in scripts that do not have #pragma strict in them. This script requires the pragma and gives the error - 'GoHome' is not a member of 'UnityEngine.Component'. target is defined corrctly as a Transform and BallScript is a script connected to the target and GoHome is a function in BallScript. What am I missing? Thank you.

Duck's answer to a similar question explains it nicely.

(Pasting, but modified for your specific question)

"BallScript" is a Component. In general, components do not have a "GoHome()" function, and the "GetComponent" function returns a value whose type is "Component".

When you're working in regular Unity's Javascript, and you try to access your BallScript component's "GoHome" function, Unity helps you by automatically changing the variable's type from "Component" to "BallScript". It does this behind the scenes, and this is called "dynamic type casting". It can do this, because "BallScript" inherits from "Component".

To use GetComponent to do what you want, you need to do this:

var ballScript : BallScript = target.GetComponent(BallScript);
ballScript.GoHome();

While the other question is specifically about iPhone, '#pragma strict' enforces the same explicit typecasting rules.


According to this thread, the quoted solution will no longer work (post-2.6). Instead, can you try:

var ballScript : BallScript = target.GetComponent(BallScript) as BallScript;

Change it to this:

#pragma strict
var target : Transform;
if (target.GetComponent(BallScript))
{
            (target.GetComponent(BallScript) as BallScript).GoHome(); 
}

Just use #pragma downcast at the top of your file

It'll fix your original issue - it allows the automatic downcasting from Component to the actual type like 2.6 did

On top of that, you could use the generic version of GetComponent which doesn't require a cast:

GetComponent.<YourScript>().Function();

which will work in strict mode without #pragma downcast