Performance. Instantiate prefabs or build those game objects from scratch in script?

Hi fellows. Before rewrite some functionality I want to be sure that will run faster. This is a mobile game. My situation is that at some point I have to build up to 2000 game objects at runtime. I know that at that moment the user will have to wait few seconds(probably), want to reduce this at maximum. Those game objects will have the transform, sprite renderer, rigidbody2D, boxcollider2D and a script. The point is what aproach will run faster, I’ve see 2 options:

  1. Make prefabs. Will be like 25. Then instantiate those.
  2. Construct the game objects from scratch in the script, then add all the components and set some variables on them.

I’ve seen a comment that option 2 is faster, but can anybody with some experience clarifies this? This choice is important for the game, because its for mobile. Thank you very much for your help.

I don’t see why Instantiate would be slower, I can understand why but don’t process all of them in one call separate them out into Coroutines so you can instantiate over an extended amount of frames rather than in 1 frame that will cause a lag as the main thread will hang while it waits for a method (in this case your instantiate method) to complete before being able to move to the next frame.

If you set it up in a Coroutine, as the game Updates the Coroutine can process in a loop over time to create the prefabs this will be a lot better performance wise. This approach will also allow you to be able to continue your game logic while the objects get created. Just be careful not to spam Instantiate / Destroy try to cache as a much as possible and reuse old objects so you don’t have to Instantiate a new one but just reactivate and move an object around that is a lot faster.

Every situation is different just be careful not to put too much stress on the CPU in one go, break them up into chunks and that will not run down your FPS.

There’s something you don’t understood. It is supposed to work that way. Must work that way. While this is happening there will be a loading screen(if takes more than a 1.5 seconds approx.). The point is I want to reduce this time by using one of the two options above. The generation of this game objects happen at the start of a scene, but they are dynamic, so must be maked on the run by scripting.

I made a test and seems that instantiating prefabs runs better. Meaby is that way because the objects are kind of complex, they have 5 components and 5 variables must be modified. If anybody have some experiencie with this, his comment will be welcome.

There shouldnt really be any difference between the two. What could make a difference though, is that, instead of instantiating/destroying objects constantly, pool the objects. Pooling is especially useful for common effects like bullets, explosions, things like that. You use them often but they generally only last a few seconds in the scene