The question is answered, right answer was accepted
C# Foreach element[,] in list problem
Hello, so Im working on a BoardGame, and I would to do an actions (Damage them in this case) to all the piece/servant (they have the script Servant attached to them) that has a certain condition (all the ally in this case) on the board, so I have FindAllAlly () that finds all the ally servants, but I cant figure out how to use the list (how to do an actions to all the Servants[i,j] in the list. Here is the script that I tried to use :
public Servant[,] Servants{ set; get; }
public List FindAllAlly () {
List<Servant[,]> allyServants = new List<Servant[,]> ();
for (int i = 0; i < tileNum; i++) {
for (int j = 0; j < tileNum; j++) {
if (Servants [i, j] != null) { // si il y a un personnage
if (Servants [i, j].isPlayer == GameManager.Instance.isPlayerTurn) {
allyServants.Add(Servants [i, j]);
}
}
}
}
return allyServants;
}
private void TestServant (){
List<Servant[,]> list = FindAllAlly ();
foreach (Servant [,] testServants in list) {
testServants.TakeDamage ( 5) // TakeDamage is on Servant script, but I cant use it, it isnt in the suggestions after typing "." so I guess it isnt getting the Servant script ?
}
}
Looked on the forums about Lists and how to use them but couldnt find any answers or didnt know that I found it. What am I doing wrong ?
Answer by hexagonius · Mar 28, 2017 at 05:23 PM
simply speaking, a list is an extensible array. in your case, it contains jaggedarrays of Servants. from what kind can see, you add servants to it and from the looks of your foreach, you just want servants, not arrays of them. make the list List<Servant>
and it should work
It worked ! Thank you , I tried with Servant alone at the beginning, but must have had a stupid error somewhere so assumed I needed arrays of them.