- Home /
going through each item of a multi-dimensional array
Hi,
i have a basic level that consists of a two-dimensional array of GameObjects. How can I delete all of them?
i did
var board:GameObject[,];
board = new GameObject[3,3];
and then i want a lil loop that wipes everything out.
for (var i = 0; i < board.length; i++)
{
for (var j = 0; j < board[i].length; j++)
{
Destroy(board[i,j]);
}
}
doesn't work, though :/ ("'length' is not a member of 'UnityEngine.GameObject'.")
Answer by Cherno · Oct 19, 2013 at 10:07 PM
You have to use GetLength(dimension) instead of length. the dimension is 0 for first dimemension and 1 for the second (and so on, if you have a 3-dimension array).
for(var x = 0; x < myArray.GetLength(0); x ++)
{
for(var y = 0; y < myArray.GetLength(1); y ++)
{
Destroy(myArray[x,y];
}
}
And it's Length with a capital L, if it were a single-dimensional array. Also it's usually unnecessary to look up the Length of an array. You should already know how many elements are in an array (just say boardSize : int = 3,) if the number of elements is variable and unknown at runtime, then you should be using a List.
"length" and "Length" both work in Unityscript. It's not that unusual to use Array.Length, since among other reasons you may have it as a public variable in the inspector, in which case you wouldn't just have the length in another variable.