I have few prefabs with sprites which I want to assign to different sorting layers. How can I do it? I am also wondering if sorting layers matter if I use a perspective camera. Do they?
1 Answer
To change the sorting layer and/or the sorting order of a sprite, just use:
SpriteRenderer mySpriteRenderer = GetComponent<SpriteRenderer>();
mySpriteRenderer.sortingLayerName = "/*[Sorting Layer Name String]*/";
mySpriteRenderer.sortingOrder = /*[Sorting Order Number]*/;
Be aware that if you use a string
different from any sorting layer that you have defined in the Tags and Layers
window, Unity will set the layer to Default
. I strongly suggest to use an enum
in your code that will store all sorting layers names.
From code, you can access the array that contains all layers by using SortingLayer.layers
Regarding your other question, yes, sorting layer and order matter regardless of what type of camera you're using, but only relative to other sprite renderers.
This means that the rendering priority between a sprite and a 3D object will depend as usual from their respective distance from the camera, whereas the rendering priority among sprites will follow the same rules as the ones when using a 2D camera.
GetComponent<SpriteRenderer>().sortingOrder = 1;
\$\endgroup\$