- Home /
(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 don't really understand what you mean. Do you want to access components of object y? In that case use y.GetComponent("name"/type) for instance y.GetComponent(Transform);
You should post some actual code. If x[0] is a gameobject, you might need to GetComponent('thescript').member()
Answer by Bunny83 · May 16, 2011 at 11:10 PM
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();
I am declaring my array as static var inventory = new Array();
I am calling it thusly: inventory[0] = i_crossbow; inventory[0].OnUse();
That last statement throws the following error: InvalidCastException: Cannot cast from source type to destination type.
I apologize for the lateness of my reply.
Answer by jahroy · May 16, 2011 at 11:10 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613134524im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Getting a variable from a GameObject inside a 2d array? 1 Answer
How do you debug arrays of objects? 1 Answer
Need help using GUI.Button/ input storage 1 Answer
Convert Array into One String (Js) 1 Answer
Help me Convert JS to C# 2 Answers