If ALL in boolean Array = true ... else ...
Hello comm unity ))) I got some problems with boolean array. I need to check if ALL at once booleans are true or false, not exact one but ALL. So, I got code: public bool [] isOpen;
bool allFalse;
for (int i = 0; i < isOpen.Length; ++i)
{
if (isOpen[i] == true)
{
allFalse = false;
Debug.Log("false");
break;
}
else
{
allFalse = true;
Debug.Log("true");
}
}
But it set allFalse = false for each isOpen = false. And I need to allFalse = false if ALL isopen = false.
Answer by MotionBrain · Feb 15, 2018 at 05:45 PM
I changed a bit from Thajacoth and it worked for me like this might be a bit too late but for the others :)
For all true:
bool allTrue = false;
foreach (bool b in boolContainer)
{
if (b)
{
allTrue = true;
}
else
{
allTrue = false;
break;
}
}
if(allTrue)
{
Debug.Log("AllTrue");
}
For all false:
bool allTrue = true;
foreach (bool b in boolContainer)
{
if (b)
{
allTrue = false;
}
else
{
allTrue = true;
break;
}
}
if(!allTrue)
{
Debug.Log("AllFalse");
}
Answer by Thajocoth · May 25, 2016 at 04:59 PM
You need to pull your false case out of the loop, like this:
allFalse = false;
foreach(bool b in isOpen)
{
if (b)
{
allFalse = true;
break;
}
}
Debug.Log(allFalse ? "true" : "false");
Tnx, but I need it to return true if ALL of isOpen = false.
You had specified that you wanted allFalse to be false if all elements of isopen are false, so that's what I gave you. What you want is the reverse, so flip true and false.
allFalse = true;
foreach(bool b in isOpen)
{
if (b)
{
allFalse = false;
break;
}
}
Debug.Log(allFalse ? "true" : "false");
In that code, allFalse is true when all values of IsOpen are false.
Answer by Norite113 · Jan 05, 2020 at 05:31 AM
join this to script and have some fun coding :P
using System.Linq;
...
//returns true if all elements in array is true
private bool AllArrayInIsTrue(bool[] Array) {
return Array.OfType().ToList().TrueForAll(x => x);
}