I am making a voxel base procedural map generator like Minecraft, and to update mesh I use new Mesh API SetVertexBufferParams/SetVertexBufferData/SetIndexBufferParams/SetIndexBufferData but my mesh doesn’t render correctly for some reason. It is NOT that my mesh isn’t drawn at all, but instead, it is drawn still but sometimes it disapears when a player camera moves or faces towards different direction but when the mesh can be still seen from the player.
My updating mesh code is like this.
_mesh.Clear();
var vertexCount = _eVertices.Count;
var indexCount = _triangles.Count;
_mesh.SetVertexBufferParams(vertexCount, _vertexDescriptor);
// pass vertices and uvs here
_mesh.SetVertexBufferData(_eVertices, 0, 0, vertexCount);
_mesh.SetIndexBufferParams(indexCount, _indexFormat);
// pass triangles here
_mesh.SetIndexBufferData(_triangles, 0, 0, indexCount, MeshUpdateFlags.
DontRecalculateBounds
);
var subMeshDescriptor = new SubMeshDescriptor(0, indexCount, MeshTopology.Triangles);
subMeshDescriptor.bounds = new Bounds(new Vector3(Extent, Extent, Extent) * ((float)Size - 1f), new Vector3(Extent, Extent, Extent) * 2f * Size);
subMeshDescriptor.vertexCount = vertexCount;
_mesh.subMeshCount = 1;
_mesh.SetSubMesh(0, subMeshDescriptor, MeshUpdateFlags.
DontRecalculateBounds
);
At first I thought my bounds calculation is incorrect, so I wrote code below to check that.
void OnDrawGizmos()
{
if (_mesh)
{
Gizmos.color = Color.red;
var bounds = _mesh.GetSubMesh(0).bounds;
// Position is the same as gameObject.transform.position. it is used to see bounds in the world space.
Gizmos.DrawWireCube(Position + bounds.center, bounds.size);
}
}
I could see the correct bounds, so I don’t know why it doesn’t work.
I tried MeshUpdateFlags.Default for SetIndexBufferData/SetSubMesh instead of manual calculation of bounds and now it gives more accurate bounds instead of my worst case bounds. But sill not work.
With using Mesh.RecalculateBounds(), I got the correct result(never disapear while the player can see it.), but the bounds is the same as using MeshUpdateFlags.Default without RecalculateBounds(). I think using MeshUpdateFlags.Default recalculates bounds instead of manually calling RecalculateBounds. That is why with that option I got accurate bounds, but I don’t know why only MeshUpdateFlags.Default doesn’t work but RecalculateBounds() works. If possible, I don’t want to use RecalculateBounds() because I think I am calculating the bounds twice now. Another reason is I want to use my manual bounds calculation to reduce bounds calculation(I can calculate it just once). I may be missing something that RecalculateBounds is doing, but I don’t know what it is.
I have used SetVertices/SetTriangles/SetUVs before those new API, so my vertices, uv, and triangles are correct.
Any advice appreciated.