Most efficient way to keep up-to-date list of object per scene in limited runtime conditions?

Long story short I have no control over project and I need to collect some data runtime and keep it up-to-date.Don’t ask WHY I do what I do, the answer will be 10x longer than question.

Anyway, on each scene change I need to find specific objects on specific layer, keep them in list and retrieve specific data on screen. Obviously iterating through 1000+ objects in scene change is madness so I tried to limit to Component search. Due to the fact some of these objects have <BoxCollider2D> disabled until it is relevant I can’t use that. Trial and error get me <MeshFilter> as the most reliable source for the first pass, which I do on scene change. To update list, I cast big OverlapBoxAll on scene during some key moments (checkpoints) with filter by LayerMask and use these results to update list when needed.

Now, before you tell me how inefficient - I know, but these are the best results I come up with, given the conditions, that affect performance less. This method works for 90% of the time but there are 10% when more frequent updates needed and by more frequent I mean at least per second. For now, only for these specific scenes I use InvokeRepeating() with OverlapBoxAll.

A few issues I can’t seems to figure out how to handle:

  1. During scene change, the search for FindObjectsOfType(typeof(MeshFilter)) as MeshFilter will return gameObjects from previous scene even though they are on their way to destruction. It is not a big deal because onGUI iterator will sort them out but it screws up the counter a bit. Check for null during the componewnt search passes as positive (object exist) so I haven’t solved how to sort them out.

  2. Is there away to do blunt raycast/overlapcast and get results regardless if collider is enabled/disabled?

  1. “gameObjects from the previous scene even though they are on their way to destruction.”
    I suspect you are using (gameObject==null)to detrmine this. Instead, use if(gameObject), As sergio7888 mentioned: This will return FALSE if the object is pending destruction.

Edit: Evidence that the above is incorrect, provided in the comments below by Bunny83

  1. I recommend AGAINST this method (unnecessary geometry computations). You would be better of simply iterating through each root scene object’s decendants. Use Unity - Scripting API: SceneManagement.Scene.GetRootGameObjects to get those root objects. Doing it this way should also eliminate issue 1.