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!
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.
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: