# Foreach / For In with a 2D array

I am using a 2D array of my GameObject type ‘Unit’.

Basically I am doing this:

``````var maxUnits:int = 25;
private var teams:Unit[,];
...
function Awake(){
// do other stuff
...
teams = new Unit[2, maxUnits];
}
..
private function SpawnUnits(count:int) {
for (var i = 0; i < count; i++)	{
// do stuff here
...
var unit:Unit = Unit.SpawnUnit();
// more stuff
teams[team, i] = unit;
}
}
``````

And then later I attempt to run a foreach or for in on this (haven’t been able to find syntax for this on a 2D array) and am not sure which one to use:

``````function ChangeTurn() {
currentTeamTurn = (currentTeamTurn == 0 ? 1 : 0);

// reset active team's units
foreach(u:Unit in teams[currentTeamTurn]){
u.Reset();
}
}
``````

I have looked around on the forums and answers board quite a bit, and even looked at some .NET docs and this wiki page about Arrays.

But cannot find the answer - can anyone help me out?

You can’t do a foreach on a 2d array - the code you’ve written is implying that it is a jagged array (an array of arrays) which would be defined, I believe, like this:

``````public var myJaggedArray : int[][];

public var jagged = [ [0,0,0,0], [1,1,1,1], [2,2,2,2] ];
``````

If you want a 2D array - then what you have is fine. If you really want to be able to do a foreach then you should redefine it as a jagged array or a single dimensional array and work out the logical X,Y within it.

I would suggest using List. so that you can actually incrementally add things to each team. Doing it that way:

``````public var teams : List.<List.<Unit>> = new List.<List.<Unit>>();
``````

There’s more information on growing collections here