Hello,
I’m working on an app in which lots of objects spawn vary quickly (around one to five objects a second). All of these objects have several scripts on them. After these objects have been in the scene for half a second to around two seconds they are destroyed. This all works fine but when I Instantiate any of my “special” objects which have the same scripts plus a line renderer, the game “jumps” for a few frames. My vary fast pace game is unplayable with this lag. Is there any way to fix this lag?
I’m also afraid of leakage because of the massive amount of objects being spawned and destroyed. Is that something that should be looked into?
Don’t destroy objects, reuse them. You will need to create a pool of objects and reuse them appropriately. There are several plugins for this on the Asset store.
If i were to load the prefabs into the scene then disable them and duplicate them when i need to spawn one, instead of Instantiating the prefab , would that fix my problem? I would still be destroying the copies when they time out.
The way to fix the problem is by not destroying anything at all. The point of a pool is that you create a small pool of objects once, then enable/disable them instead of creating and destroying old ones. So, let’s say your objects are enemy ships. You’d create ten or twenty of them (or however many you’d need available at one time) and place them in a list or stack, disabled and with default values. When you need to “make” a ship, you pop one out, configure it and enable it. When you need to “destroy” one that’s active, you disable it, reset it back to its defaults and put it back into the pool.
For this task, there are multiple pool managers on the asset store’s shelves. Alternatively, if this is a one off, you can roll your own easily enough.
Thanks Metabble.
I wrote my own pool manager script and it’s working great! I now pool my rocks and meteors because I “Spawn” around 5 a second. and I Instantiate power ups because they are rare and it doesn’t seem like it’s worth it to pool them.
Great! Also, you’re right that it’s not usually worth pooling rare objects like powerups, especially if you aren’t using a global pooling system that can automatically pool everything. Bullets, enemies and other objects that get instantiated and destroyed really frequently in large numbers is usually enough.