- Home /
check if each element in string is true simultaneously?
this script only checks if/when the first item in the string is true. How do you make it check if ALL elements in the string are true?
var blahString:GameObject[];
for(blah in blahString) if (blah.GetComponent(script).on = true) (Unlock goal)
thanks
Answer by Eric5h5 · May 17, 2012 at 05:37 AM
That's not a string, that's a GameObject array. You can't do anything literally simultaneously, but you can loop through the array and check each element. If one is false, cancel the loop and don't perform the action. If they are all true, then the loop completes and you can perform the action.
That's the strange part, I tried cancelling if one was false, but for some reason, it still executes if just the first element is true.
Then you programmed your logic wrong. Should probably post the code.
var Components : GameObject[];
function Update(){
for(others in Components)
if(others.GetComponent("StoryTrig").On == false){
return;
}else{
print("Completed!");
}
}
I did some tinkering, and found out that the 'for each' code will only do a first depth search.
In your suggestion, checking if any are false will work, but saying that the loop will complete else wise is incorrect because it will still return TRUE when just one of the elements becomes true.
When you look at the code, your still basically asking 'if(Components[0] is on/off)', then depending on that boolean, then it will only check the next component in line.
I tried this in the game, and when one component becomes true, it will both print both "completed!" and "off!".
I am trying to get it to check all elements. Is there a way to specifically say "if(Components[ALL].GetComponent("StoryTrig").On == true)" ??
Like eric says, you can't actually do anything simultaneously (without very carefully scheduled multithreading, but let's not go there). In this case, it's simply the return condition that needs to be tweaked- you need to make sure that every single one of the components is in a single state.
Now, what you have to realise here, is that that is exactly equivalent to checking for whether one of the objects is in the wrong state! So, all you need to do here is invert your logic:
for(others in Components)
if(others.GetComponent(StoryTrig).On){
return; // One of the objects was active, returning
}
}
// got to the end of the loop without returning:
print("Completed!");
This way, the only way to get to the last line is if none of the components are active.
In fact, if you simply made the array at the top an array of 'StoryTrig' type, you could avoid the 'GetComponent' call entirely!