I have a list of gameObjects and I want to perform some operations on them. At some point, they will eventually get destroyed. What is the best way of checking if one of the objects in that loop is null without breaking the loop? i.e. When one of them is null, the loop will just skip it and keep going. Please avoid proposing to use an array with a counter instead.
for (var objective : GameObject in objectives)
{
//Do code
}
If you are concerned that objectives will at some point hold null values this will execute safely:
for (var objective : GameObject in objectives)
{
if (objective == null) {
continue;
}
//Do code
}
However if you are concerned that the code within each iteration may cause objective to be null this is more appropriate:
for (var objective : GameObject in objectives)
{
if (objective != null) {
//some code
}
if (objective != null) {
//more code
}
}
When working around constraints it is often good to challenge your design to see if it could be improved.
Questions I would be asking myself are: Why am i avoiding a for loop with counter? Why is objectives allowed to contain null values? Why not clean these null values first?
There can be very good reasons for doing it the way you are, but it is always good to consider alternatives as well.