Instantiating objects causes lag.

Hello,

I am currently creating a game where you must continue on a course until you die. This means that pieces must be infinitely instantiated as the player progresses. Currently, each time the player passes a level piece, a new level piece is instantiated 10 level units in front of him and the piece that has been passed is destroyed. This means there are always 10 pieces on the screen at all times. However, the player gets through each level piece quickly, and a new piece must be generated on average every second. Obviously, this leads to this occasional lag spike which kills the gameplay. I have read that I could instantiate 10 of each piece at the beginning (totalling up to 60 pieces) and then move them to the necessary spot but I feel as if that could be worse. Any suggestions?

No, it wouldn’t be worse. Using an object pool instead of constantly instantiating/destroying is much more efficient. But you’d only need 10 objects, not 60. Change the attributes of existing pieces as needed.

–Eric

But you see, each piece is actually a seperate piece modelled in blender. There can be up to 10 objects on the course at once. Theoretically, then, there can be 10 of the same type of piece on the course at one time. Therefore I must have 60 pieces instantiated. Sadly, this seems to crash Unity as they are all being instantiated at once. I can’t even imagine how I’m going to be able to put this on mobile.

If you can post your code that is pre-spawning the objects we might be able to help with that crash. I’ve done much more instantiating than that with no issues before. How big are these objects that are being instantiated?

Would perhaps coming up with some sort of level seed business (and therefore the entire level, although infinite, is predetermined) allow for faster instantiation?

It wouldn’t speed up instantiate itself. But if you’re spending lots of cycles trying to figure out which piece to spawn next you might see a speed increase.

I don’t think you’ll get much help without posting some relevant code samples.

I am using a toon shader, so polygons aren’t too important for this game. I lowered the polygon count substantially in each mesh and each looks nearly the same, but they instantiate with no lag. Thank you for your help.

Nope. Instantiate 10 only, and change the meshes on the fly as required.

There’s no way simply instantiating a few objects does this, since you can instantiate hundreds of thousands of objects without any problems, aside from the fact that having so many obviously is slow.

–Eric