Performance while spawning trees

I’m trying to keep track of tree position in my game because the player is able to chop them down. Hence, when I save and load the game, the tree must remain chopped down. Currently, I’m achieving this through a saveload function which spawns in the unchopped trees on loading the game. However, considering that there might be a thousand trees or more, how can I make this more performant? Thanks. The game is 2D btw.

Did you already try to only spawn trees when they become visible? You could also or additionally spread spawning across multiple frames.

How would I go about implementing spawning trees only when they are visible? It’s a 2D top down game. I was thinking I could add a 2D circle collider as a trigger around the player, but if I only store the tree’s position and type in the save file, how do I detect that the player is close enough to spawn the tree?

My tree spawning load is in a coroutine, but this still causes massive frame drops when spawning.

You test if the tree circle is inside the camera frustum (or close to it), where the frustum is just a rectangle in 2D. You can shrink the tree circle to just a point and inflate the camera rectangle by the tree radius, which allows you then to test “is point in rectangle”, using things such as Rect.Contains().

EDIT: You could use a CullingGroup for that, so you get a callback from Unity when the tree becomes visible. I believe this is a neat approach to this problem and hands the “heavy work” regarding visibility checks to the engine.

If you process all trees at once, it doesn’t make a difference if it’s a coroutine. What I meant with “spread over multiple frames” is that you process less trees per frame. A coroutine is actually quite useful to implement this. If you need to spawn 100 trees in total, you could spawn 10 trees per frame. This means, after 10 frames, all trees are spawned. If this works depends how the game actually works and might not be suitable for every game, because “trees might lag behind”.

Hmm I might need to look into how culling groups work, but that assumes that I have the spheres in an array. How can I supply this array with the corresponding tree type and position on load game for the trees that are not destroyed only?

I could spawn in all my trees together with a sphere for each tree to add to a bounding sphere array in the game manager. Then, when the sphere is not visible, set the respective tree’s visibility to false. Does that sound viable for a 2D scenario? Not a lot of culling group tutorials out there…