I was somewhat excited about finally getting around to building a development blog because now I can post the few little things I’ve discovered about using Unity3d along the way. One of the more interesting things I had fun building was my object recycler.
It turns out calling Instantiate() on a prefab creates a massive amount of overhead on a smartphone. This wasn’t even remotely a concern of mine when I started working on Eros because I was strictly using the PC development environment from the beginning, with the idea that I’d start testing on a device once I had something worth looking at. After I acquired my iPhone and Android development licenses the first thing I noticed after throwing a build on my phone’s was that everything slowed down to a crawl. A bit of googling here and there about optimizing Unity for smartphones and I came across this well written blog which gave me some decent hints about what I needed to implement.
When a new object is instantiated via the queue it either pops a recycled object off the queue, or instantiates a new one in the case that the queue is empty. It has the ability to prime the queue with a pre-specified amount of Instantiate()’ed objects so that all of that happens during level load time and not while the game is running. There’s also an object spawn limit parameter, with the idea that there might be a situation where a few objects still look as good as all of them being spawned (in my case explosions).
The main pieces of the system can be viewed here. The first is the linked list for tracking and storing the objects. Next is the core script which is attached to queue-able game objects. The final bit is the queue system itself, which gets attached to an object in the scene (a special prefab, or the camera would do fine). When a CoreBehaviour object is built it also contains a reference to the queue so it can spawn other objects, or despawn itself to the queue on destruction.
I’m somewhat torn about using strings as indexes due to the fact that they apparently have poor performance, but by the time I discovered this I had built way too many objects to bother going back and changing things. I’m not sure how much performance I would gain anyways, but my somewhat uneducated guess would say not much at all.
A configured queue system object looks somewhat like this.
Unfortunately I don’t have the performance numbers in front of me right now, but needless to say this was an immense help in reducing overhead and making my game lag free on smartphones. Having access to a Unity Pro license was also a large help in regards to debugging this and many other problems I encountered. I’m not sure how people could release a smartphone action game without running it through the profiler.
The next system I’ll post about is my AudioManager, which addresses another unforeseen performance bottleneck I didn’t consider until later down the road.