Could I get an explanation of object pooling and how to do it?
Sorry for being such a beginner :/. But I am having a hard time understanding how to write an object pooling script in C#. I understand the general concept that the game is to instantiate a fixed quantity of objects at the start and then replace the instantiation and destroying with activating and deactivating. But I just can't successfully write a working script. I just want to make my game smoother with object pooling.
If anyone is willing to explain anything, it would be greatly appreciated!
Whether it's difficult or not is trivial, it's a great learning experience. Take what hexagonius mentions below, and maybe expand on it by resetting the pooled object's state when it's released/returned so it's in the same state it would be if it were just spawned when it's needed again (using an interface perhaps).
Things to experiment with: Write an interface for pooled things so anything can be poolable Create extension methods to the interface for common operations (like Spawn and Release) * Create a pool manager that basically maintains several pools of things
Have fun!
Answer by hexagonius · Sep 12, 2015 at 10:35 PM
You can create a pool class (not deriving from MonoBehavior) which has the following fields and methods:
constructor; taking in the Item to be pooled and an int for how many of them
Stack, and List for available and used objects
method Item GetItem()
method ReturnItem(Item item)
the constructor fills the stack with items and disables them when GetItem is called, remove it from the stack, add it to the list and return it enabled. when ReturnItem is called, check the list for the item, and if found disable it, remove it from the list and add it to the stack.
Answer by pako · Sep 13, 2015 at 09:43 AM
It can be quite challenging for a beginner to create a pooling script. Maybe you should consider a pooling solution from the Assets store, where you can find decently priced, or even free packages available. Here are the Asset Store search results for "Pool" search term: