(JS) Calling a member function of an object in an array

In javascript, I have an array "x", the first element of which is an instance of object "y". Elsewhere, I try to call a member function of y like so:

`x[0].member();`

It fails. How can I make this work?

I guess you declared your array like this:

var x : Array;

The Array class can only hold elements of type Object. Everything is an Object so you can store everything in that array, but if you access an element the compiler only knows it's an Object. You have to cast the reference into your actual type.

(x[0] as MyScriptType).member();

The Array class is very slow due to dynamic typing. Native arrays are the fastest but they can't be resized that easily. The best alternatives are the generic classes like `List.<>`

var x = new List.<MyScriptType>();

The members of such a list have the type you specified at creation time, in my example "MyScriptType". With such a list your line above would work.

x[0].member();

That should definitely work. I do it all the time.

I wonder if your array needs to be typed (declared to be a specific type) or if it has to be a built-in array.

The way you word your question it sounds like your array might contain objects of different types. I could see how this could cause issues for UnityScript, which can be loose with it's types.