- Home /
The question is answered, right answer was accepted
How do I check if all booleans in an array are true?
So, basically what I'm trying to do is write a bit of code that checks if all my objectives are complete, and if so, load a scene that says you've won.
My current mission checker is working fine, so when kill all enemies, mission A being complete returns true, but what I want to do is check if every mission is complete, so that's A, B, C, etc, all returning true, and then doing something when that happens.
This is the code that checks if each mission's requirements are met, and returns true if so. I just don't know where to go next..
using UnityEngine;
using System.Collections;
public class Objectives : MonoBehaviour
{
public gameObjectives[] MissionList;
int objectiveDone = 0;
void Update()
{
//Debug.Log (MissionList.Length);
for (int i = 0; i < MissionList.Length; i++)
{
int missionsDone = 0;
for (int j = 0; j < MissionList[i].objectiveObject.GetComponentsInChildren<EnemyBuilding>().Length; j++)
{
if(MissionList[i].objectiveObject.GetComponentsInChildren<EnemyBuilding>()[j].done)
{
missionsDone++;
}
if(missionsDone == MissionList[i].objectiveObject.GetComponentsInChildren<EnemyBuilding>().Length)
{
//Debug.Log("FINISHED OBJECTIVE " + i);
MissionList[i].isComplete = true;
}
}
}
}
}
Edit: I have made it work using a very clunky method.
if ($$anonymous$$issionList[1].isComplete == true && $$anonymous$$issionList[2].isComplete == true && $$anonymous$$issionList[3].isComplete == true && $$anonymous$$issionList[4].isComplete == true)
{
Application.LoadLevel("winScene");
}
Is there a neater way of doing this?
Answer by daleth90 · May 20, 2016 at 05:32 AM
private bool IsAllMissionComplete() {
for ( int i = 0; i < MissionList.Length; ++i ) {
if ( MissionList[ i ].isComplete == false ) {
return false;
}
}
return true;
}
I think you know how to use this function. :)
Answer by aditya · May 20, 2016 at 05:41 AM
bool[] missionArray;
bool allMissionsComplete = true;
missionArray = new boll[3]{true, true, true};
foreach(bool currentMission in missionArray){
if(!currentMission){
allMissionsComplete = false;
}
}
if(allMissionsComplete){
// ALL MISSIONS ARE COMPLETE
}else{
// NOT ALL MISSIONS ARE COMPLETE
}
You should put a break after line 7 since it'S pointless to iterate through the remaining elements if one is false.
i thought of the same but dropped the idea thinking that it might not be a good idea to FORCE a loop to stop ... just asking, is it okay to ter$$anonymous$$ate loops if their objective is completed ?
Yep.
In this case, especially, once you've reached your objective state, you can be done. Since it's assumed that the boolean will be true until proven false, the instant it's been proven false is the moment you can bail out of the loop.