0
0
Unityframework~15 mins

Sorting layers and order in Unity - Deep Dive

Choose your learning style9 modes available
Overview - Sorting layers and order
What is it?
Sorting layers and order in Unity control how 2D objects are drawn on the screen. They decide which objects appear in front or behind others. This system helps organize visuals so that scenes look correct and clear. It is especially important for games with many overlapping sprites.
Why it matters
Without sorting layers and order, objects would draw randomly, making scenes confusing or visually broken. Imagine a game where a character appears behind a tree even when standing in front of it. Sorting layers solve this by letting developers control the visual stacking order, improving player experience and game clarity.
Where it fits
Before learning sorting layers, you should understand Unity's basic 2D setup and sprites. After mastering sorting layers, you can explore advanced rendering techniques like custom shaders or 3D layering. Sorting layers fit into the broader topic of Unity's rendering and scene organization.
Mental Model
Core Idea
Sorting layers and order define the visual stacking of 2D objects so the game draws them in the right front-to-back order.
Think of it like...
It's like stacking transparent sheets with drawings: the sheet on top covers the ones below, so you see the top drawing first.
┌───────────────┐
│ Sorting Layer │
│  (Background) │
│  Order in Layer: 0 │
├───────────────┤
│ Sorting Layer │
│  (Characters) │
│  Order in Layer: 5 │
├───────────────┤
│ Sorting Layer │
│  (Foreground) │
│  Order in Layer: 10 │
└───────────────┘

Objects in higher layers or with higher order values appear on top.
Build-Up - 7 Steps
1
FoundationWhat are Sorting Layers
🤔
Concept: Sorting layers group 2D objects to control their drawing order in Unity.
In Unity, sorting layers are named groups you assign to sprites or 2D objects. Each layer represents a visual group like Background, Characters, or UI. Objects in higher sorting layers draw on top of those in lower layers, regardless of their position in the scene.
Result
Objects assigned to the 'Characters' layer will always appear in front of those in the 'Background' layer.
Understanding sorting layers helps you organize your scene visually by grouping objects that should appear together.
2
FoundationOrder in Layer Explained
🤔
Concept: Order in layer sets the drawing priority of objects within the same sorting layer.
Within a sorting layer, objects can have different 'Order in Layer' values, which are integers. Higher numbers draw on top of lower numbers. For example, two characters on the same layer can be ordered so one appears in front of the other by setting their order values.
Result
A sprite with order 10 draws over a sprite with order 5 in the same sorting layer.
Order in layer lets you fine-tune which objects appear in front when they share the same sorting layer.
3
IntermediateSetting Sorting Layers in Unity Editor
🤔
Concept: You can create and assign sorting layers using Unity's editor interface.
In Unity, open the Tags & Layers settings to add new sorting layers by name. Then select a sprite or 2D object and set its sorting layer and order in the Sprite Renderer component. This controls how Unity draws that object relative to others.
Result
Your object visually moves in front or behind others based on the assigned sorting layer and order.
Knowing how to create and assign sorting layers in the editor is essential for practical scene setup.
4
IntermediateSorting Layers vs Z Position
🤔Before reading on: do you think changing an object's Z position affects its draw order in 2D? Commit to yes or no.
Concept: Sorting layers and order override the object's Z position for 2D rendering order.
In 2D mode, Unity ignores the Z position for draw order and uses sorting layers and order instead. Changing Z position alone won't change which sprite appears on top. This prevents confusion when objects overlap visually but are at different depths.
Result
Objects with higher sorting layers or order draw on top, even if their Z position is behind others.
Understanding this prevents bugs where changing Z position doesn't affect visibility as expected in 2D.
5
IntermediateUsing Sorting Groups for Complex Objects
🤔
Concept: Sorting Groups let you treat multiple sprites as one unit for sorting purposes.
When an object has many child sprites, a Sorting Group component can be added to the parent. This groups all children into one sorting layer and order, so they move together visually. It avoids parts of the object drawing incorrectly in front or behind other objects.
Result
All child sprites respect the parent's sorting layer and order, appearing as a single visual unit.
Sorting Groups simplify managing complex objects made of multiple sprites.
6
AdvancedDynamic Sorting Order via Script
🤔Before reading on: do you think you can change sorting order at runtime with code? Commit to yes or no.
Concept: You can change sorting layers and order in code to adjust draw order dynamically.
Using C# scripts, you access the SpriteRenderer component and set its sortingLayerName and sortingOrder properties. This allows effects like characters moving in front of or behind objects based on game logic or player position.
Result
The object's visual stacking changes immediately during gameplay as code updates sorting properties.
Dynamic sorting order enables responsive visuals that adapt to gameplay situations.
7
ExpertSorting Layers Internals and Performance
🤔Before reading on: do you think having many sorting layers affects game performance? Commit to yes or no.
Concept: Unity uses sorting layers and order to batch draw calls efficiently, but excessive layers can impact performance.
Internally, Unity sorts sprites by layer and order before rendering. Grouping sprites reduces draw calls, improving performance. However, too many layers or frequent changes can cause more sorting work and reduce efficiency. Balancing visual needs and performance is key.
Result
Proper sorting layer use improves rendering speed; misuse can cause slowdowns.
Knowing the internal sorting helps optimize both visuals and game performance.
Under the Hood
Unity maintains a list of all 2D sprites each frame. It sorts them first by sorting layer priority, then by order in layer, and finally by their position if needed. This sorted list determines the draw order on screen. The rendering engine then draws sprites from back to front, so higher layers and orders appear on top visually.
Why designed this way?
This system was designed to separate visual stacking from 3D positioning, simplifying 2D rendering. It allows artists and developers to control visuals without changing object positions, which can affect physics or gameplay. The layered approach also supports batching for performance, grouping similar sprites together.
┌─────────────────────────────┐
│ All Sprites in Scene        │
├──────────────┬──────────────┤
│ Sorting Layer│ Order in Layer│
├──────────────┼──────────────┤
│ Background   │ 0            │
│ Characters   │ 5            │
│ Characters   │ 10           │
│ Foreground   │ 0            │
└──────────────┴──────────────┘
        ↓ Sorted by Layer and Order
┌─────────────────────────────┐
│ Draw Sprites Back to Front  │
│ Background (0)              │
│ Characters (5)             │
│ Characters (10)            │
│ Foreground (0)             │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does changing Z position alone reorder sprites in 2D? Commit yes or no.
Common Belief:Changing an object's Z position changes its draw order in 2D scenes.
Tap to reveal reality
Reality:In Unity 2D, sorting layers and order in layer control draw order, not Z position.
Why it matters:Relying on Z position causes confusion and bugs where sprites appear behind or in front incorrectly.
Quick: Can two objects on different sorting layers have the same order in layer and still draw correctly? Commit yes or no.
Common Belief:Order in layer alone determines draw order, regardless of sorting layer.
Tap to reveal reality
Reality:Sorting layers have higher priority than order in layer; layers override order values.
Why it matters:Misunderstanding this leads to unexpected layering where objects appear behind others despite higher order values.
Quick: Does adding many sorting layers always improve visual control without downsides? Commit yes or no.
Common Belief:More sorting layers always make layering easier and better.
Tap to reveal reality
Reality:Too many sorting layers can hurt performance and complicate management.
Why it matters:Excessive layers increase sorting overhead and can reduce game frame rates.
Quick: Does the Sorting Group component change the sorting layer of child sprites individually? Commit yes or no.
Common Belief:Sorting Group changes each child's sorting layer separately.
Tap to reveal reality
Reality:Sorting Group treats all children as one unit with a single sorting layer and order.
Why it matters:Misusing Sorting Group can cause unexpected layering if you expect children to sort independently.
Expert Zone
1
Sorting layers are internally represented by integer IDs, not just names, which affects sorting speed and lookup.
2
Changing sorting layers or order frequently at runtime can cause performance hits due to re-sorting and draw call changes.
3
Sorting Groups can nest, but nested groups combine their sorting orders additively (by summing offsets), which can be tricky to predict.
When NOT to use
Sorting layers are not suitable for 3D objects or complex 3D scenes; use Unity's Z-buffer and camera depth instead. For UI elements, use Canvas sorting order and layers. For very dynamic layering, consider shader-based solutions or custom render queues.
Production Patterns
In production, developers use a small set of well-defined sorting layers (e.g., Background, Midground, Foreground, UI) and control order in layer for fine adjustments. Sorting Groups are used for characters with multiple sprites (body parts, equipment) to keep them visually consistent. Dynamic sorting order scripts adjust layering based on player position or game events.
Connections
Painter's Algorithm (Computer Graphics)
Sorting layers implement a form of the Painter's Algorithm by drawing objects back to front.
Understanding this algorithm explains why sorting order matters and how Unity decides what to draw first.
Layered Cake (Cooking)
Both involve stacking layers in a specific order to achieve the desired final appearance.
Knowing how layers build visually in cooking helps grasp why sorting layers control visual stacking in games.
Version Control Branching
Sorting layers group related objects like branches group related code changes.
This analogy helps understand grouping and prioritizing elements in a complex system.
Common Pitfalls
#1Objects appear behind others even when moved forward in Z.
Wrong approach:sprite.transform.position = new Vector3(x, y, -1); // expecting draw order change
Correct approach:spriteRenderer.sortingLayerName = "Foreground"; spriteRenderer.sortingOrder = 10;
Root cause:Misunderstanding that Z position does not affect 2D draw order; sorting layers control visibility stacking.
#2Child sprites of a complex object draw out of order.
Wrong approach:No Sorting Group component on parent; children have different sorting layers/orders.
Correct approach:Add Sorting Group component to parent to unify children's sorting.
Root cause:Not grouping child sprites causes Unity to sort them individually, breaking visual unity.
#3Too many sorting layers cause performance drops.
Wrong approach:Create dozens of sorting layers for every small visual difference.
Correct approach:Use a limited set of sorting layers and adjust order in layer for fine control.
Root cause:Overusing sorting layers increases sorting complexity and draw calls.
Key Takeaways
Sorting layers and order in layer control the visual stacking of 2D objects in Unity, independent of their position.
Sorting layers group objects into visual layers, while order in layer fine-tunes draw order within those groups.
Z position does not affect draw order in 2D; relying on sorting layers prevents common layering bugs.
Sorting Groups help manage complex objects by treating multiple sprites as a single visual unit.
Efficient use of sorting layers balances visual clarity and game performance.