Sorting Group
The Sorting Group is a component that alters the order in which Renderers are rendered. Conventionally renderers in Unity will be sorted by several criteria such as Order in Layer or distance from camera. However, it was not possible to ensure that a group of renderers that share a common root be sorted together. Well, until now…
Having renderers that belong to a common root render together is extremely useful. A common use case in 2D games are with complex characters.
Here we have a 2D Character with multiple renderers in a hierarchy. Character is in a single Sorting Layer and uses multiple Order in Layers.
It is then saved into a prefab and subsequently cloned multiple times during game play. Before the advent of Sorting Group, these complex 2D character will face great trouble when they overlap on screen. You will likely find their body parts ‘interleaved’ with each other.
Here’s how it looks like when 2 complex characters overlap without Sorting Group.
However, the desired outcome is to have all the renderers of a character render together and then followed by the next character. With a Sorting Group component added to the root of the character, their body parts no longer get mixed up.
Setting Up Sorting Group
To use the Sorting Group component, simply add it to the object’s root. The Sorting Group itself does not have any visual representation and it also does not have any dependencies on other renderers. It could even be added to an empty GameObject. Once added to an object, any renderers that’s on the GameObject and it’s descendants will be rendered together.
How are Sorting Groups sorted?
They are sorted like every other renderer, using Sorting Layer and Order in Layer.
How are children of Sorting Group sorted?
The descendants of the Sorting Group are also sorted according to the standard sorting criterions such as Sorting Layer and Order in Layer. However, there is one major difference. During the sort, the descendants of Sorting Group will only be sorted against other descendants of the most immediate Sorting Group. In other words, the Sorting Group creates a local sorting space only for its descendants. This allows each of the renderers inside the group be sorted using the same simplistic Sorting Layer and Order in Layer but localized to the containing Sorting Group.
Nested Sorting Group
Sorting Group can be nested. A nested Sorting Group will be sorted just like a regular renderer against other renderers in the same group. Do note however, branches in the hierarchy that does not have any Sorting Group will be flattened.
One Last Thing
Any renderers that are descendant of a Sorting Group will be considered as ‘alpha’ objects and thus rendered after all the opaque objects.