- Home /
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?
I am currently just invoking the array with a normal for loop, which fits the bill in the sense that it is allowing me to find every object I need.
As far as being able to optimize my code, I would like to change this to a foreach type loop.
Answer by whydoidoit · Nov 17, 2012 at 11:11 PM
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
Yes I looked into using Lists - but couldn't find any docs regarding their use with a multi-dim array.
I tried your code above and get this error: expecting >, found '>>'.
Any ideas?
[Also - thanks for that link!]
Ugh you are right, looks like JS can't actually make a generic list of a generic list (why I don't know - .NET can do it!)
You'd have to do it like this -
#pragma strict
class Unit
{
}
class Units
{
var units : List.<Unit> = new List.<Unit>();
}
public var listOfLists = new List.<Units>();
function Start () {
listOfLists.Add(new Units());
listOfLists.Add(new Units());
listOfLists[0].units.Add(new Unit());
listOfLists[1].units.Add(new Unit());
}
Your answer
Follow this Question
Related Questions
How to set a value for each level without using a switch statement 2 Answers
StartCoroutine for each object in a foreach() Loop 1 Answer
Change global state in list 1 Answer
Foreach - what am I doing wrong? 1 Answer
Getting all objects with a tag and inserting them into an array of gameobject 1 Answer