Pooling WaitForSeconds in Unity

Unity’s built in pooling
WaitForSeconds
Cached WaitForSeconds
  1. It does not support variable times, e.g. new WaitForSeconds(Random(1, 10))

A Pool of WaitForSeconds

There are different ways around these problems, but the method I chose for Xevious was to create a Pool of WaitForSeconds.

Pool of WaitForSeconds

The implementation

Sometimes when you write code you have a dilemma. In this case mine was should I use the in-built pooling or write my own? My problem with the inbuilt methods is that they require the pooled object to have an empty public constructor and guess what, WaitForSeconds does not have one. Now I could get around that this by having a pool of YieldInstruction which WaitForSeconds derives from. But if I do that then it gets a bit muddy because other YieldInstructions do not require a float and I would need to write code to wrap it and…well it just feels a little icky to me.

Takeaway

To drag out the old ‘Peter Parker principle’, pooling is a great power but it is a great responsibility too. It can be used for lots of situations where you find yourself wanting to reuse something rather than continually destroying and recreating it. However, you have to monitor it carefully because it can end up accelerating the problem you were trying to avoid.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store