top of page
  • Writer's pictureVishwas Gagrani

Changing the sorting order or z-index of game objects in Unity

Updated: Jan 5

To change the sorting order of game objects in Unity we can add the Sorting Group component to that game object. There are two fields that need to be set for a sorting group.

  1. The sorting order number ( e.g. 0,1,2 etc...) where 0 means the bottom. The game object with larger value will show on top of game objects with smaller values.

  2. The sorting layer, i.e. the layer of the game object.

Once each game object has got a sorting-group component and values specified their display order can be controlled using a script as follows.



using UnityEngine;
using UnityEngine.Rendering ;

public class ChangeSortOrder : MonoBehaviour
{
    public GameObject a;
    public GameObject b;
    public GameObject c;

    void Start()
    {

    	print(a.GetComponent<SortingGroup>().sortingOrder);
    	print(b.GetComponent<SortingGroup>().sortingOrder);
    	print(c.GetComponent<SortingGroup>().sortingOrder);
    	
        changeOrderOfDisplay();

        print(a.GetComponent<SortingGroup>().sortingOrder);
        print(b.GetComponent<SortingGroup>().sortingOrder);
        print(c.GetComponent<SortingGroup>().sortingOrder);


    }

    public void changeOrderOfDisplay()
    {

    	a.GetComponent<SortingGroup>().sortingOrder = 2;
    	b.GetComponent<SortingGroup>().sortingOrder = 1;
    	c.GetComponent<SortingGroup>().sortingOrder = 0;
   }

}



download file: https://fbb9a3bc-35c8-4d82-b3cf-6cbe24ec492d.usrfiles.com/archives/fbb9a3_e3cebfb4b4b5478db6da47ce44d478a7.zip

79 views
bottom of page