Unity3D – Multidimensional Arrays – Jagged Arrays
One Dimensional Array
A 1D (one dimensional) Array is something like that:
var strings = ["First string", "Second string", "Third string"];
or if you want:
// Array Start
var mycars = new Array();
mycars[0] = "Saab"; // Notice: the first value is 0
mycars[1] = "Volvo";
mycars[2] = "BMW";
// Array End
Debug.Log(mycars[0]); // Result is Saab
Notice the index inside square brackets [i], has only one dimension.
Try to think about a line:
[0] [1] [2]
OR
[Saab] [Volvo] [Bmw]
Multidimensional Array
A Multidimensional Array has a two dimensional grid coordinated to store variables.
A Multidimensional Array is always rectangular!
Example ONE:
#pragma strict
public var multiDimensionalArray: int[,] = new int[2,2]; // 2x2 -> 4 cells
function Start () {
// Array Values
multiDimensionalArray[0,0] = 10;
multiDimensionalArray[0,1] = 20;
multiDimensionalArray[1,0] = 30;
multiDimensionalArray[1,1] = 40;
Debug.Log(multiDimensionalArray[0,1]); // Result is 20
}// END Start()
NOTICE new int[2,2]; -> it means 4 cells
Try to think about a grid with 2D coordinates, the 4 cells are:
[0,0][0,1]
[1,0][1,1]
OR
[10][20]
[30][40]
Example TWO:
#pragma strict
public var multiDimensionalArray: int[,,] = new int[2,2,2];
function Start () {
// Array Values
multiDimensionalArray[0,0,0] = 10;
multiDimensionalArray[0,0,1] = 20;
multiDimensionalArray[0,1,0] = 30;
multiDimensionalArray[0,1,1] = 40;
multiDimensionalArray[1,0,0] = 50;
multiDimensionalArray[1,0,1] = 60;
multiDimensionalArray[1,1,0] = 70;
multiDimensionalArray[1,1,1] = 80;
Debug.Log(multiDimensionalArray[1,0,1]); // Result is 60
}// END Start()
Jagged Array (Matrici Irregolari o Array ‘Frastagliati’)
A Multidimensional Array is always rectangular, in a Jagged Array, each of the ‘rows’ is a different length
#pragma strict
public var myJaggedlArray = [
[0,1,1,0],
[1,0,0,1],
[1,0,0,1],
[0,1,1,0]
];
function Start () {
}// END Start()