Triangle Sorter

Buy now on Asset Store!

Very often, in particular for mobile games, objects like foliage are rendered with alpha blending. This produces good looking semi-transparent objects and their silhouettes but brings in one crucial problem – sorting of triangles. Some triangles that are further from the camera pop up in front of those that are closer which is incorrect. This problem is partially solved by Unity’s sorting mechanism on a per-object basis what does not solve at all the problem with triangles within a single object (like a tree which usually is placed in the scene as a single mesh).

Here is where Triangle Sorter comes handy. It’s a tool that, during a mesh preprocessing step (upon import), sorts triangles of that mesh along a specified axis. This way, for instance, triangles can be sorted top-down for a tree making the top-most leaves be rendered after the bottom-most ones have been rendered. This ensures correct triangles sorting order on a per-triangle basis when the camera is looking down the tree.



The tool does not expose any graphical interface. The only input that can be provided is the axis along which the triangles will be sorted. This axis is defined as a 3D vector in the 124-th line of the source code file TriangleSorter.cs. Different meshes might need different axis, a constant one might not suit them all. This can be solved in many ways on your own. One way is to encode the axis in the mesh’s file name and decode it upon the import (OnPostprocessModel function in TriangleSorter.cs). Also, the file name of the mesh file can contain information whether to sort the mesh in the first place.


The scene at TriangleSorter/Assets/BlossomGames/TriangleSorter/Examples/Levels/test.unity contains a simple tree that has been sorted upon import along the Z-axis so that it looks well when looked at from above.

Please note here that the tree is aligned with the Y-axis and yet it was sorted along the Z-axis. That is because the tool sorts based on the original triangles positions, without taking into account the mesh’s transform. You can see in the Hierarchy view that the tree meshes’ Transform components actually hold rotations that rotate the tree from being aligned with the Z-axis to being aligned with the Y-axis.