So I have this topdown 2D game I’m creating with a large overworld, covered with trees, rocks, bushes, etc… which the player can destroy for resources. (think Forager, Stardew Valley, etc)
So the things I had to tackle were object pooling, since there are hundreds of prefabs needing to load in and out as the player moves around… and of course I also need chunk loading to deal with segmenting the overworld into pieces that a computer can actually handle.
I have implemented chunk loading, and I also implemented object pooling… and while everything works, there’s one nagging issue that’s been bothering me… and that’s when you reach the “edge” of a chunk and step into the next one, it’s needing to load 3 new chunks and unload 3 old chunks. That’s cool, but this is taking upwards of 40-50ms and causes a noticeable stutter when moving around between chunks.
At first I was enabling/disabling objects which I noticed in the profiler was causing considerable slowdown… SetActive takes a lot of resources… so I figured, okay, I’ll just set the object’s transform to something way off screen and add it back to the pool, so it can just get assigned a new position when I take it from the pool.
This works well, and considerably improved performance… but as I stated earlier… it’s still at 40-50ms when moving to new chunks… and that is because of… SetParent. See, my whole chunk loading system works off the idea that I place 9 “chunk” objects in my scene in a grid, and when I need to load in bushes, trees, rocks from the pool, they get parented to their respective chunk. The reason being that it’s super easy to save and load chunks this way since I can just save the hierarchy of the chunk. So if I want to save everything in chunk X/Y, I would just save all of the data inside the chunk (all of the prefab objects) and when I want to load, I just load it all in. This is a really simple way of making a chunk loader… but the problem is all of the objects need to be parented to their chunks in order to save/load.
The problem is SetParent is taking the biggest hit to my performance… but I don’t see a solution to this. I mean I could assign some tag or variable to each object to associate it with a specific “chunk” but then I would need to loop through all objects and compare that variable to save them to their proper chunk file… which I’m not sure is going to be a faster solution.
Take note that I’m saving chunks as they unload, since I want to save any changes the player made.
So how would I manage to load/unload these objects without parenting them to a chunk, but while keeping them “assigned” to a particular chunk? If I can avoid parenting all together, it’s going to significantly cut down on the performance hit. What other method of chunk loading could I possibly do which would be more efficient and not involve parenting?