In Unity with Javascript I can make an array of arrays, where each of the arrays are of different sizes, but can someone tell me how to access the individual arrays?
var array1 : Array = [1, 2, 3, 4];
var array2 : Array = [5, 6, 7];
var array3 : Array = [8, 9, 10, 11, 12];
var arrayOfArrays : Array = [array1, array2, array3];
When I try the following:
for(var row : Array in arrayOfArrays){ }
I get the error on the for loop:
InvalidCastException: Cannot cast from source type to destination type.
Does someone know how to access the individual arrays in arrayOfArrays?
Are you sure you’re copying/pasting things correctly? Restated, is there something hidden/different in your actual code as your example works like a charm for me. For example:
function Start () {
var array1 : Array = [1, 2, 3, 4];
var array2 : Array = [5, 6, 7];
var array3 : Array = [8, 9, 10, 11, 12];
var arrayOfArrays : Array = [array1, array2, array3];
for(var row : Array in arrayOfArrays){
Debug.Log(row[0]);
}
}
If I use that and hit play I see 1, 5, 8 in the Console window as expected.
You are right! I am investigating.
I had defined the arrays as:
var array1 : Vector3[ ] = [1, 2, 3, 4];
which produced the cast error. Once I changed the definition to how
I had stated the problem as
var array1 : Array = [1, 2, 3, 4];
then it worked fine as you noticed.
Sometimes just another pair of eyes helps. Thanks!
Awesome, I’m glad I could help! 