- Home /
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;
}
Answer by duck · May 19, 2010 at 08:45 PM
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
}
}
Thanks a lot, but I have one similar problem now...
I'm trying to use:
if (GetComponent("ScriptB").myArray.length > 0 && myRect.Contains(Input.mousePosition))
and it gives me the error:
'Contains' is not a member of 'Object'.
You wouldn't happen to be getting 'myRect' out of your array would you? If so, you probably need to do the same casting shenanigans. Eg: `var myRect : Rect = myArray[n];`