- Home /
How can I do a foreach loop for an array of booleans?
I have an array of booleans in C#, and after a specific input I would like to loop through and set all of these booleans to false. But I am getting the following error with the loop code:
Cannot assign to buttonBoolean' because it is a
foreach iteration variable'
And here is the code:
public bool[] inputBool;
foreach (bool buttonBoolean in inputBool) {
buttonBoolean = false;
}
The booleans in the array all come from the one script which is attached to one gameobject in the scene. I've used a loop similar to the above to for example turn off/deactivate all the gameobjects in an array, so I'm not sure why it isn't working for turning off all the booleans in an array.
If i'm not wrong, you can't change any properties of variable while using foreach. Use simple for loop to do that.
Answer by Lovrenc · Jul 29, 2013 at 08:19 AM
The problem is not that your array is boolean, it is that you are trying to assign value to buttonBoolean in foreach loop. It is read-only as every foreach iteration variable is. Check this
You could do this instead:
public bool[] inputBool;
for(int i = 0; i < inputBool.Length; i++) {
inputBool[i] = false;
}
Yes that's it! Thanks a lot you're a champ. Btw the link you posted above doesn't have a proper url ;)
As a side note, just for the hell of it: The default value of bool is false. So unless this has to take place on a regular basis because you need the array reset to all false, then there's no reason to do it.
Yes of coarse, the above is only a snippet of a much larger piece of code.