Search code examples
arraysmultidimensional-arrayunity-game-engineunityscriptcellular-automata

Making a 2D Array in UnityScript by making an array of arrays


So I'm working in Unity 3D with UnityScript trying to make a cave generator using cellular-automata. Here is my problem, I've created two variables, width and height, and they need to be the size of my 2D array. I've also created a function to generate the map upon startup, so the array needs to be initialized upon startup. I know I need some kind of for loop using .length and one of the variables, but I'm not entirely sure how to do this. Any help would be great!


Solution

  • If all of the rows in your 2D array are the same length you don't need to write a loop, simply check the length of an arbitrary row i.e

    var arr = [
      [1, 2, 3],
      [1, 2, 3],
      [1, 2, 3],
      [1, 2, 3],
    ];
    var height = arr.length; //4
    var width = arr[0].length; //3
    

    An example where you would need to loop through is if all of the widths were of differing lengths i.e

    var arr = [
      [1, 2, 3],
      [1, 2, 3, 4]
    ];
    
    var widths = [];
    for (var i = 0; i < arr.length; i++) {
      widths.push(arr[i].length);
    }
    console.log(widths); // [3, 4]
    

    Here's how you generate a 2d array given the height and width

    var height = 5,
    width = 4;
    
    var arr = [];
    for (var i = 0; i < height; i++) {
      arr[i] = [];
      for (var j = 0; j < width; j++) {
        arr[i][j] = "x";
      }
    }
    console.log(arr);
    
    // [ [ 'x', 'x', 'x', 'x' ],
    //   [ 'x', 'x', 'x', 'x' ],
    //   [ 'x', 'x', 'x', 'x' ],
    //   [ 'x', 'x', 'x', 'x' ],
    //   [ 'x', 'x', 'x', 'x' ] ]