Another way to Destroy GameObjects.,Remove a GameObject without affecting the clones and the project.

Hello everyone. I want to add some boxes(GameObjects) to pallets. Because boxes spawn all the time, I want to “destroy” (vanish/disappear etc.) the older boxes. I used Destroy(box) and Destroy( but it affects my project and pauses it. Also it sends this message Destroying assets is not permitted to avoid data loss . Is there any other way to do something like that ??? Thanks.

Destroy is a painful process and it will cause more lag than usual because of garabage collection. This is why pooling is suggested. A simple solution is keeping your boxes in a list and when you done with any of the boxes just disable it’s gameObject with SetActive(false);. And when you want to spawn a box with different values just get a random inactive item from list, set it’s values and activate it again.

With this error your “box” is probably a reference to a prefab, you cannot destroy a prefab in runtime. You have to keep references to all the boxes you spawn and destroy individual spawned boxes instead.

What you should really do is read about object pooling. This sounds exactly like what you are trying to achieve. There are many tutorials and code samples that could help you. It’s a really simple concept which can quickly improve your flow here and optimize it a lot.

What’s the idea behind object pooling. Instantiating and destroying objects is quite expensive in terms of performance. What pooling does can be broken down into few steps:

  1. Spawn few objects you need (inactive)
  2. When you request an object your pool gives you one of the already spawned objects
  3. When you “destroy” your object you deactivate it and give it back to the pool
  4. If pool is empty and you want another object you have two choices
  5. First: automatically “destroy” oldest spawned object and immediately give it back
  6. Second: instantiate another object. This one is easier, it’s harder to make a mistake, but there can create a situation when you spawn more and more objects leading to memory problems