- Home /
The question is answered, right answer was accepted
How can I check values of all array/List quickly
I have a List of gameobjects, each gameobject in the List has an accesible "error" member assigned to it during simulation.
I'd like to trigger a (one) global bool value to true, when the value of "error" in gameobjects in the List is between -0.05 and 0.05.
I'd do this, setup an array of int, matching the number of entries in List, check the entry of List one by one, if condition met, assign 1. If the total of 1s in the int == entry in List than switch a global bool to true.
My approach is rather long and winding. My question is, is there a shorterway?
Why not use a list of booleans ins$$anonymous$$d of integers? Or, better still, why not just make a single integer that counts the number of times the condition was met? That way, you don't have to iterate over the list and then the array.
without seeing your code, it's not easy to suggest something better (shorter isn't necessarily that). it's unlikely that you'd need an array of int's to store each test condition, but again, without seeing your code, it's not 100% clear what you're trying to achieve.
Answer by ArkaneX · Apr 07, 2014 at 10:03 AM
You can use LINQ methods (Any or All), e.g.
bool allErrorsAreInRange = !gameObjects.Select(x => x.GetComponent<YourComponentWithErrorInfo>().error)
.Any(e => e < -0.05f || e > 0.05f);
You need using System.Linq
for above code to work.
The drawback of this code is that GetComponent
might be called multiple times, up to the number of elements in your list. But in your current code you have the same problem (well - not exactly, since you do your check for each element, while above LINQ code does it until it finds invalid value). If you want to use it often, I would consider creating a list of YourComponentWithErrorInfo
instead.
I've accepted your answer based on
"... If you want to use it often, I would consider creating a list of YourComponentWithErrorInfo ins$$anonymous$$d."
Follow this Question
Related Questions
A node in a childnode? 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
GetComponent for gameobject list alternative 1 Answer
Adding Item object to Inventory List 0 Answers
Help with C# Arrays / lists / etc - 1 Answer