Star Maverick 64 - Tue, 04 May 2021 13:44:16 GMT
This is not a very interesting update but something I knew I had to do at some point.
I added object pooling to Space Soup for the bullets and impacts.
Technical details follow.
Object pooling for those who don’t know is the practise of keeping around a pool of objects to use and re-use for what would otherwise be short lived, one off objects. Creating brand new bullet objects many times a second and also destroying them as they hit or expire is problematic. It is a lot of work to do the creation and destruction but also it causes lots of work for the garbage collector and fragments memory. This means frame rate spikes as the garbage collector kicks in every so often, and more memory usage for the application overall.
Adding pooling means when an object would otherwise be destroyed forever we just disable and hide it and then when we need a new one we grab a hidden one, reset it’s state such as position, and re-enable it. This saves on object creation/destruction work as we only create new objects when there are no recycled ones to use, moving and re-enabling is much less work.
So to implement this I watched this video by Jason Weimann for a refresher and some inspiration on how to achieve it simply in Unity and then wrote my own basic object pool. I have a GameObjectPool component that keeps a queue of objects and also a static collection to find pools for different prefabs by name. I also have a Poolable component that keeps track of the pool an object was spawned from so it can be simply told to go to “sleep”. Then on being awoken it will automatically play any particle systems and audio clips. It also has hookable callbacks on sleep and awake so I can do special things for certain prefabs. (For example I need to clear the trail renderer on my bullets so they don’t show a path from where they died to where they next spawned.) It’s really basic and I might need something better as time goes by; but it’s working great for me for now.
You can see in the animation; the pool grows as new objects are needed. The objects dim grey when they are deactivated and ready for recycling, and then become active again as needed.