I am making a 2D dungeon crawler which has pretty large levels. This means that although there will rarely be many objects on the screen at any given time, the entire world has quite a lot of creatures, and I am starting to see serious slowdowns. Specifically caused by a large number of gameobjects tagged as “enemy”
Each enemy object has a collider and a rigidbody, as well as some simple scripts with logic in the update method. All of which can safely be ignored when not on screen.
To make sure Unity does not spend any time on anything that is not visible, in particular on collision and physics logic which I think is the main culprit here, I was trying something like this from the main game loop, set to execute as the first script on each frame redraw:
GameObject [] enemies = GameObject.FindGameObjectsWithTag ("enemy");
foreach (GameObject go in enemies)
go.SetActive(go.renderer.isVisible);
However, that does not work since disabled objects wont be collected during the next pass using FindGameObjectsWithTag, and as they are disabled, I suppose the rendererer wont even check if they are potentially visible or not. And, I am not sure if this approach is good practice anyway…
How to best make sure Unity does not spend any time on objects that are not on screen?