Strongly Typed Javascript on iOS

My app just got riddled with errors when I went to build and run for iOS. I found out it was because of the lack of 'strongly typed javascript' via here. The errors all seem to be coming from wherever I use the 'GetComponent'. Here's how I'm doing it...

//declaring variable
var manager = GameObject.FindWithTag("TagName");
//calling function
manager.GetComponent(GameManager).someFunction;

How can I make this a strong type?

2 Answers

2

GetComponent returns Component, so it needs to be cast to the correct type. The easiest way is to use generics:

//declaring variable
var manager = GameObject.FindWithTag("TagName");
//calling function
manager.GetComponent.<GameManager>().someFunction;

You can also do it the "hard way":

manager.(GetComponent(GameManager) as GameManager).someFunction;

hey thanks mate. this worked wonders.

Add #pragma strict to the top of your file to make debugging easier and to force yourself to use strict typing.

Rule N1 is to never simply use a var anymore. Always declare it's variable, like so:

#pragma strict
var manager : GameObject = GameObject.FindWithTag("TagName");

This is completely wrong, sorry. Type inference takes care of this for you. Whether you use "var manager : GameObject =" or "var manager =", since FindWithTag returns GameObject, that's used to infer the type of manager. So it makes no difference at all. (This is the same in C#.) The actual problem is that GetComponent returns Component, which needs to be cast to the correct type.

@Eric5h5, I may have solved with this: var someScript : ScriptName = GetComponent (ScriptName); someSCript.function; the error disappears but i have a lot to run through before i know it's solved. thoughts?