Search code examples
c#unity-game-enginegame-developmentzposition

All objects being the same z position despite different z offsets


I have cards which are meant to appear on top of each other but for some reason they are all in the same z position, despite me increasing the offset at the end of each iteration.

The offset does successfully grow but when looking at the cards in scene their z position is always 0.

Given that the z offset is larger with each iteration, each card should be on top of the one before it. I tried changing the offsets to more drastic values (like 0.5 instead of 0.03) and this didn't solve it.

I've tried including tableauPos[i] before the transform and that doesn't fix it either.

Code for placing the cards:

for (int i = 0; i<7; i++)
{
    float yOffset = 0;
    float zOffset = 0.03f;
    foreach(string card in tableaus[i])
    {
        //yield return new WaitForSeconds(0.01f);
        GameObject newCard = Instantiate(cardPrefab, new Vector3(tableauPos[i].transform.position.x, tableauPos[i].transform.position.y - yOffset, transform.position.z - zOffset),Quaternion.identity, tableauPos[i].transform);
        newCard.name = card;
        newCard.GetComponent<Selectable>().row = i;
        if (card == tableaus[i][tableaus[i].Count-1])
        {
            newCard.GetComponent<Selectable>().faceUp = true;
        }

        yOffset += 0.3f;
        zOffset += 0.03f;
    }
}

Cards in game:

Cards in game

Their side profile in scene:

Their side profile in scene

Diagonal profile in scene:

Diagonal profile in scene

And if I move the camera a certain way, which card is visible changes.

Same cards as prior but can see king now:

Same cards as prior but can see king now


Solution

  • If you're using SpriteRenderers for the cards, you need to use settings such as Sorting Layer and Order in Layer rather than the Z position in the transform.

    The higher the number, the closer the GameObject looks to the Camera. (docs)

    SpriteRenderer sorting layer and order in layer

    More info: https://discussions.unity.com/t/how-to-set-sprite-rendering-order-for-a-card-game/937796

    The default 3D Renderers draw stuff according to Z depth - distance from camera.

    Sprites draw according to Sorting Layer and Sorting Depth (properties of the Sprite Renderer)

    There's also this if you want to get more sophisticated: Unity Manual - 2D Renderer Sorting