- Home /
Check to see if any bool instance is true?
Hello all,
Literally all day I've been tearing my hair out trying to figure out how to do this. I have a set of GameObjects with one script attached, which has a bool. I also have a controller which automatically adds each of the GameObjects with this script to it.
The behaviour I want is for if any number of these bools is set to true, some audio starts playing but currently if one or more is set to true, it's being overridden by the others still being false. I'd like to know how to check each of the scripts from the values added to the list and check each of their bools individually and if just one is set to true, start the audio regardless of whether the others are false.
Thank you!
I'm not sure I understand the problem, because you seem to have all the elements to solve this problem:
If you have a controller that has a reference to each of the scripts, you can just iterate through the collection which stores the script, and if any bool
is true, you break out of the iteration, and play the sound.
For example, if the controller stores instances of SomeScript
in a List<SomeScript> someScripts
, and you have access to the bool flag
on SomeScript
(for example because it is public
), then you can do the following in the controller script:
private void Update () {
if (ShouldPlaySound()) { someAudioSource.Play(); }
}
private bool ShouldPlaySound () {
for (int i = 0; i < someScripts.Count; ++i) { if (someScripts[i].flag) { return true; } }
return false;
}
As you can see, this solution is very obvious, so I think I misunderstood the problem. Also note that this will start playing the sound in every frame. $$anonymous$$aybe that's the problem?
Answer by misher · Sep 04, 2018 at 03:53 PM
Grab all references of you components ( scripts ) into array or list, iterate trough it and check that bool for each, if found first true, DoSomething() and break the loop. To get array of components you can use:
FindObjectsOfType<MyScript>();
or (if you know all componnets are in children of game object you have you controller script on)
GetComponentsInChildern<MyScript>();
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
question about array or list of boolean 1 Answer
How to make the Boolean equal to true for only one object 1 Answer
A node in a childnode? 1 Answer
List of List of Booleans function giving weird results 1 Answer