CodeBlanks Logo Icon CodeBlanks

Sprite sorting

Learn 2D layer sorting with Sorting Layer and Order in Layer.

Sprite Sorting and Layers

In 2D games, object depth is primarily managed through draw ordering rather than the Z axis. Sorting Layer establishes broader category layers (like Background, Foreground), while Order in Layer determines draw priority within that layer.

// Setting sorting layer and order via code
SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.sortingLayerName = "Characters";
sr.sortingOrder = 5;

This guarantees that characters appear in front of backgrounds and behind foreground foliage.

Layer Ordering Logic

Layers render sequentially: The top-most Sorting Layer renders first at the back, while the bottom-most layer in the project settings renders in front.

// Layer stack example:
// 1. Background (Floor)  -> Order: 0
// 2. Characters (Player) -> Order: 10
// 3. Foreground (Grass)  -> Order: 20

A well-planned sorting structure provides a flawless sense of depth in 2D scenes.

Practice Print sorting layer information

Assign "Foreground" to layer and 5 to order. Print Layer: Foreground | Order: 5 to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // layer ve order değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string layer = "Foreground";
        int order = 5;
        Console.WriteLine("Layer: " + layer + " | Order: " + order);
    }
}

Expected output

Layer: Foreground | Order: 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Between two sprites in the same Sorting Layer, which one is rendered in front?

  • The one with a numerically higher Order in Layer value Correct answer
  • The one positioned at the very top of the Hierarchy list
  • The one taking up more disk space in file size
  • The one with a lower or negative Order in Layer value

Explanation: Objects with higher Order in Layer values are always drawn on top of lower ones.

2 Set layer order

Question
sr.____ = 10;
Answer
sr.sortingOrder = 10;

Explanation: The sortingOrder property on SpriteRenderer governs rendering priority within a layer.

3 Sorting concepts

Term Meaning
Sorting Layer Render layer grouping visuals logically
Order in Layer Integer setting draw order in layer
Background Backmost layer forming background
Foreground Foremost layer overlaying elements

All lessons in Beginner