Mesh API - SetIndexBufferData Help

Hi All,

I’m currently converting a procedural mesh generation tool to the new API. I’m on 2019 LTS and using the Job System. The SetVertexBufferData is all working fine but SetIndexBufferData is just giving me a mesh with the correct number of vertices but 0 triangles. If I use SetIndices (the commented out code at the bottom) with the same data it works just fine. I thought it might have something to do with .AsArray() so I explicitly created a NativeArray with no change. I’m also using uint as the integer type.
Am I doing something wrong or is there a bug with SetIndexBufferData?
Any help would be appreciated.

        public static void SetMesh(UnityEngine.Mesh mesh, MeshData meshData)
        {
            int vertexCount = meshData.VertexData.Length;
            int indexCount = meshData.Indices.Length;

            mesh.Clear();

            mesh.SetVertexBufferParams(vertexCount, GetVertexLayout());
            mesh.SetVertexBufferData(meshData.VertexData.AsArray(), 0, 0, vertexCount);

            mesh.SetIndexBufferParams(indexCount, IndexFormat.UInt32);
            mesh.SetIndexBufferData(meshData.Indices.AsArray(), 0, 0, indexCount);

            //NativeArray<uint> triangles = meshData.Indices.AsArray();
            //mesh.SetIndexBufferData(triangles, 0, 0, indexCount);

            //mesh.SetIndices(meshData.Indices.AsArray(), MeshTopology.Triangles, 0, false);

            mesh.RecalculateNormals();
            mesh.RecalculateTangents();
            mesh.RecalculateBounds();
        }

You should add SubMesh to mesh.

1 Like

Thanks. That works fine. It’s not immediately apparent from the documentation that it’s required but perhaps it’s my lack of understanding of submeshes :).

Careful with those calls. Recalculate normals and tangents is not done (and I recommend doing it yourself if you can because that is VERY slow). Also, you’re settings the vertex buffer and index buffer without the flags so that it doesn’t recalculate bounds all the time. It is recalculating them 3 times in your case, I believe.
You should set the flag to all those methods to not recalculate, and do it at the end, when you call the last SetIndexBufferData without the flag. there’s no nee to call recalculate bounds after that.