0
0
Unityframework~5 mins

Sorting layers and order in Unity

Choose your learning style9 modes available
Introduction

Sorting layers and order help decide which objects appear in front or behind others in a 2D game scene.

When you want a character to appear in front of the background but behind the UI.
When you have multiple objects overlapping and want to control which one is visible on top.
When creating a layered scene like a forest with trees in front and behind the player.
When you want to organize objects visually without changing their position in the game world.
Syntax
Unity
spriteRenderer.sortingLayerName = "LayerName";
spriteRenderer.sortingOrder = number;

sortingLayerName sets the layer name where the sprite belongs.

sortingOrder sets the order inside that layer; higher numbers appear on top.

Examples
This puts the sprite in the Background layer at order 0, so it appears behind others.
Unity
spriteRenderer.sortingLayerName = "Background";
spriteRenderer.sortingOrder = 0;
This puts the sprite in the Characters layer with order 5, so it appears in front of lower orders.
Unity
spriteRenderer.sortingLayerName = "Characters";
spriteRenderer.sortingOrder = 5;
This puts the sprite in the UI layer with a high order to appear on top of most objects.
Unity
spriteRenderer.sortingLayerName = "UI";
spriteRenderer.sortingOrder = 10;
Sample Program

This program sets three sprites to different sorting layers and orders. The background is behind, the player is in front of the background, and the UI is on top of both.

Unity
using UnityEngine;

public class SortingExample : MonoBehaviour
{
    public SpriteRenderer backgroundSprite;
    public SpriteRenderer playerSprite;
    public SpriteRenderer uiSprite;

    void Start()
    {
        backgroundSprite.sortingLayerName = "Background";
        backgroundSprite.sortingOrder = 0;

        playerSprite.sortingLayerName = "Characters";
        playerSprite.sortingOrder = 5;

        uiSprite.sortingLayerName = "UI";
        uiSprite.sortingOrder = 10;

        Debug.Log($"Background Layer: {backgroundSprite.sortingLayerName}, Order: {backgroundSprite.sortingOrder}");
        Debug.Log($"Player Layer: {playerSprite.sortingLayerName}, Order: {playerSprite.sortingOrder}");
        Debug.Log($"UI Layer: {uiSprite.sortingLayerName}, Order: {uiSprite.sortingOrder}");
    }
}
OutputSuccess
Important Notes

You can create and manage sorting layers in Unity's Tags and Layers settings.

Sorting order only matters within the same sorting layer.

Use sorting layers and order to avoid changing object positions just to control visibility.

Summary

Sorting layers group objects to control their visual stacking order.

Sorting order sets which object appears on top within a layer.

Use these to organize your 2D scene visually without moving objects.