Search Unity

Array of Arrays

Discussion in 'Scripting' started by aerende, Jul 16, 2009.

  1. aerende

    aerende

    Joined:
    Apr 27, 2009
    Posts:
    316
    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?
     
  2. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    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:

    Code (csharp):
    1. function Start () {
    2.  
    3.   var array1 : Array = [1, 2, 3, 4];
    4.   var array2 : Array = [5, 6, 7];
    5.   var array3 : Array = [8, 9, 10, 11, 12];
    6.  
    7.   var arrayOfArrays : Array = [array1, array2, array3];
    8.  
    9.   for(var row : Array in arrayOfArrays){
    10.     Debug.Log(row[0]);
    11.   }
    12.  
    13. }
    If I use that and hit play I see 1, 5, 8 in the Console window as expected.
     
  3. aerende

    aerende

    Joined:
    Apr 27, 2009
    Posts:
    316
    You are right! I am investigating.
     
  4. aerende

    aerende

    Joined:
    Apr 27, 2009
    Posts:
    316
    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!
     
  5. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    Awesome, I'm glad I could help! :)