Sprite Renderer, False Order in Layer

Hello everyone,

I’m currently working on a 2D isometric game and encountering an issue with the SpriteRenderer.

I have a “warehouse” with 12 piles, and each pile can store up to 20 items. When an item prefab (WoodLogs) is stored, the “SortLayerWarehouse” function calculates the “Order in Layer” through code, and it seems to work correctly.

    public void SortLayerWarehouse(int RessourceStorageNumber)
    {
        float precisionMultiplierWarehouse = 5f;

        Debug.Log(RessourceStorageNumber + " " + transform.position.y + " " + ((int)(-transform.position.y * precisionMultiplierWarehouse)));


        spriteRenderer.sortingOrder = ((int)(-transform.position.y * precisionMultiplierWarehouse)+ RessourceStorageNumber);
 
        Debug.Log(RessourceStorageNumber + " " + transform.position.y + " "+ spriteRenderer.sortingOrder);


    }

!(http://

)

However, randomly, the wrong “Order in Layer” is sometimes assigned to the item prefab. In my example, it should be 1116.

!(http://

)
According to the code and debug information, the calculation appears to be correct. However, when I click on the item prefab, the “Order in Layer” is 1099. It seems that the “ResourceStorageNumber” was forgotten to be added. This happens randomly in each pile, and the “ResourceStorageNumber” is consistently missed. I tried running the code under LateUpdate, but it didn’t help. Does anyone have an idea what might be causing this?

!(http://

)

You probably should not be assigning anything to the prefab.

Instead assign it to the instance you created.

Name your variables clearly so you can tell: spriteRenderer is ambiguous between prefab / instance.

Thanks for the response. I made a mistake; I didn’t mean the actual prefab, I meant the instantiated prefab.

From your screenshots it looks like you’re assigning all your objects a different sorting order. There’s a better way to get things sorting.

Use a Transparency Sort Axis of (0, 1, 0). From your screenshot, it looks like this setting is correct already, but for completeness: if you’re using the 2D Renderer, go to its asset and this setting will be there. If you’re not then it’ll be in Project Settings/Graphics.

What (0, 1, 0) does is say to the renderer: “Sorting by y exclusively.” Objects with a larger y-value will sort toward the back. Then all the objects that sort against one another can be on the same order/layer.

Here’s a video showing that:

No discussion of sorting is complete without mentioning there’s the extremely useful Sorting Group component: Unity - Manual: Sorting Groups

Thank you, that solved my problem. I hope you have a great day.