Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

2D Fixed AND Variable-Length Array

Discussion in 'Scripting' started by John-B, Aug 15, 2014.

  1. John-B

    John-B

    Joined:
    Nov 14, 2009
    Posts:
    1,250
    I need a 2D array that is a fixed length in one dimension and variable length in the other. In other words, I need a fixed-length array with 8 elements, each of which is a variable-length array. These variable arrays start out empty, so their lengths would initially be zero. I'm translating some old Director/Lingo code, and it's trivial to do it there.

    I normally use lists when I need variable length, but you can't create an empty, fixed-size list. Can you? If so, I can't figure out how. Or maybe a JS array of lists? None of those things seem to work.

    The only solution I can see right now is to use 8 separate lists, but there are several of these and that would really complicate things (like no more loops). Any suggestions?
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Code (javascript):
    1. var myArray = new List.<int>[8];
    2. for (var i = 0; i < myArray.Length; i++) {
    3.     myArray[i] = new List.<int>();
    4. }
    5. myArray[0].Add (42);
    6. Debug.Log (myArray[0][0]);
    You would never use a JS array for anything, ever. ;)

    --Eric
     
  3. John-B

    John-B

    Joined:
    Nov 14, 2009
    Posts:
    1,250
    Thanks. I already tried something like this, but I don't think I initialized the array correctly.