Chris R.
Chris R.

Reputation: 597

Gizmos.DrawCube display bug when multiple cubes drawn near each other

When I draw multiple cubes using Gizmos.DrawCubeto visualize some 3D tiles, I end up with a bunch of cubes inside out. It's called from Editor Code. Here is the code for the call:

private void OnDrawGizmos() {
    foreach (Vector3Int position in positions) {
        Gizmos.DrawCube(position * Const.tileSize, Const.tileVectorSize);
    }
}

Here is the display bug:

Display bug

But everything is ok when _position only contains 1 cube Everything is ok with only one cube

Edit: It also happens with few cubes drawn :

enter image description here

Any idea what is going on and how to correct it ?

Upvotes: 5

Views: 1302

Answers (1)

Pluto
Pluto

Reputation: 4081

This is not actually a bug. The gizmos don't write to the depth buffer. What that means (and what you see in the image) is gizmos being drawn on top of each other regardless of whether they are behind another gizmo. Maybe there is some way to enable depth buffer write or zWrite on gizmos, now you know what to look for.

What you could do in the meantime is try the Painter's algorithm. This is just sorting the gizmos from furthest from the camera to closest before you draw them.

private void OnDrawGizmos()
{        
    var sorted = positions.OrderByDescending((x) => Vector3.Distance(Camera.current.transform.position, x));

    foreach (Vector3Int position in sorted)
    {
        Gizmos.DrawCube(position * Const.tileSize, Const.tileVectorSize);
    }
}

And this is what it looks like: enter image description here

Upvotes: 5

Related Questions