Loop through partially filled Array of Objects

Hi

I have game, it has many objects 500+, I store each created objects in this array and remove from array the objects that are destroyed.

Now my Question is: How do I loop through this array/database?

I need to activate/deactivate objects that are close/far enough from Player.
(So also inactive objects has to get active later)

The problem is ofc, the array will have holes like objectDatabase[5] = null but objectDatabase[7] = someObjectStored.

If I make foreach loop, it will crash ofcourse. Any ideas please?

(Dont suggest object pooling pls its completely impractical for me)

just insert a line like this at the start of the loop:

for(int i = 0; i < array.Length; i++) {
    if(array *== null) {*

continue;
}
//whatever you want to do if there’s actually something stored in this position
}

or, with a foreach loop:
foreach(GameObject go in array) {
if(go == null) {
continue;
}
//whatever you want to do if there’s actually something stored in this position
}
This will skip all the following code inside the loop and go on with the next array element.

If you’re using C# you could use a HashSet. It both allows you to do a foreach, and also to Add and Remove elements with reasonable speed. An array is probably not the best choice for something which grows and shrinks dynamically.