Why am I getting this error when accessing a variable or function on my script using GetComponent - 'x' is not a member of 'UnityEngine.Component'?

Hey,

I have a script in which I try to access the length of an array in another .js script. Frustratingly, an error keeps coming up, saying: 'myArray' is not a member of 'UnityEngine.Component'.

I've been trying to solve this for several hours and I'm at my wit's end...

The code looks something like this (ScriptA.js and ScriptB.js are components of the same object, 'Code'):

ScriptA.js

function Update () {
   if (GetComponent("ScriptB").myArray.length > 0) {
      //Execute some stuff
   }
}

ScriptB.js

var myArray = new Array();

function OnGUI () {
   if (someButton) {
      myArray.Push(new myClass);
   }
}

myClass.js

class myClass {
   var intA : int;
   var intB : int;
}

You need to cast the result of GetComponent to the correct type. The correct type is the 'type' of your script - i.e. your script's name.

Common ways of doing it look like this:

function Update () {
   // put the reference into an explicitly typed var
   var thisScriptB : ScriptB = GetComponent("ScriptB");
   if (thisScriptB.myArray.length > 0) {
      //Execute some stuff
   }
}

or like this:

function Update () {
   // use 'as' to convert the type before using it:
   if ((GetComponent("ScriptB") as ScriptB).myArray.length > 0) {
      //Execute some stuff
   }
}