Reasonably efficient y-sorting in Unity with 2D Toolkit

It’s been quite some time since I’ve posted anything – we’ve been busy launching Letter Quest Remastered on Steam, launching a game at my day-job, and all kinds of other things. I’ve finally found a bit of time to start getting back into some coding, so it’s about time I start posting on here again! 🙂

I’ve been learning how to use 2D Toolkit more effectively in Unity – Letter Quest Remastered uses 2D Toolkit for most of the in-game art, with all of the animations being handled by the awesome Spine animation tool.

The new game idea that I’m thinking about tackling next requires sorting all characters and enemies on the screen by y-value, so that things that are closer to the bottom of the screen will appear over top of things that are further up (back).

Without doing any y-sorting, you get results like this:


You can see that there’s no sorting going on, slimes are overlapped at random (actually based on the order that they were created).

With a bit of y-sorting, we get a much nicer result:


Unity makes it very easy to do this sort, it’s actually just one line of code in an Update function in each class, and takes advantage of a renderer’s sorting order:

void Update()
mRenderer.sortingOrder = (int)(mScreenHeight - this.transform.position.y);

I can get away with simply using the transform’s y-position, because with the way I have everything set up, that actually corresponds to the bottom of my enemies. You might have to do a bit of offsetting based on the height of your enemies – you generally want a sort like this to be based on the bottom of objects.

To make this more efficient, you could set the sortingOrder of all objects from a single Update function in a manager class, and you could probably get away with calling it 10 to 20 times a second, instead of every frame. I don’t need the performance (yet!), and I also have other logic in Update for each enemy, so it makes sense to do this in each enemy’s Update function.

Leave a Reply

Your email address will not be published. Required fields are marked *