Issues with GetComponent

Hi everyone,

I’ve done this before without issue so I’m not sure where I’m going wrong.

Say I have a GO with 2 scripts attached and I want to manipulate a variable in script foo from script bar. In script bar I would write:

var otherScript : foo;
function Awake() {
      otherScript = gameObject.GetComponent(foo);
}

But all I end up with is Cannot convert UnityEngine.Component to ‘foo’. What am I overlooking here?

var otherScript="foo";
function Awake() {
      otherScript = gameObject.GetComponent(otherScript);
}

Ew, no. Don’t use strings unless you have to, they’re slower.

You need to use “gameObject.GetComponent(foo) as foo”, but I’m not sure why, as I usually don’t have to do this in my code.

Try adding one or more of the following to the top of your script and see if they remove the message:

#pragma implicit
#pragma downcast

Sorry for not following up on this earlier.

Removing #pragma strict from the script appears to make it work correctly. Did I read somewhere that this isn’t needed in 3.0 anymore because Unity implies it?

No, in fact it’s more necessary now. Unity iPhone used to have an implicit “#pragma strict”, but now that iOS publishing is part of Unity, that doesn’t happen anymore. But you still get code errors if you try to use dynamic typing when publishing for iOS, so it’s a good idea to always use #pragma strict when doing iOS (and probably Android) development.

The issue is that #pragma strict is more strict in Unity 3, so in order to avoid downcasting, you have to explicitly define the type that GetComponent is being cast to, by doing “otherScript = gameObject.GetComponent(foo) as foo;”. Either that or you can enable downcasting by using #pragma downcast.

–Eric

Makes sense. Thanks for clarifying!