How to return an index value from an array
How would I go about getting the index of an element at an array if it meets particular criteria. For example I have two arrays of 6 boolean elements which are performing similar functions. For the first only one element can ever be true and I would like to get the index value of the element which is true. For the second any number could be true and I would like to flag all which are true. So far creating a for loop and iterating through each has created some problems when I try to display the values. Either I don't get the values past the first element that is true or I can only get the last value.
Post your loop code and we can see what might have gone wrong.
for (int y = 0; y < 6; y++){
// int values
burgherstxt[y].text = tile.burgher[y].ToString();
peasantstxt[y].text = tile.peasants[y].ToString();
warriorstxt[y].text = tile.warrior[y].ToString();
uniquestxt[y].text = tile.unique[y].ToString();
// boolean values
if (tile.influence[y]){
influencetxt.text = "Player " + (y + 1);
} else {
influencetxt.text = "None";
}
}
I have 6 players, each of which can have pieces on a given tile. This loop works fine for the arrays of ints as I am just displaying their values corresponding to a text box. However for referencing the array of booleans (tile.influence[]) I want to return the index of the value which is true (only one can be true). If none are true then I want to display that as well. As I recall this particular loop will only check the last value and display that. It occurs to me that it is changing the text value 6 times as it iterates through each which would explain why I only get the last value to display. I tried adding in a return line for when it is true but that led to other problems. Ideally I would like to place this outside of my loop altogether, hence my question about flagging an index value where the element is true.
Answer by Darkgecko777 · Feb 19, 2016 at 10:11 PM
Sorted it out. While I was not able to determine the index of a given value as per my original question I did solve my issue. As well, the documentation for arrays and lists would indicate that there is some way to find an index but it looks like I can bypass that altogether. I put the following line after my loop rather than use the else in the loop.
if (!tile.influence.Contains(true)){
influencetxt.text = "None";
}
Now if all values return false I get the message I want.
Your answer
