Error: lastVertex < GetVertexCount ()

I’m not sure what this error means. It occurs when I assign triangles array to mesh object:

...
var mesh = new Mesh();
mesh.vertices = _vertices.ToArray();
mesh.triangles = _triangles.ToArray();
...

The problem is that I create hundreds of meshes but the error occurs very seldom, and I cannot trace what causes it. If I knew what the message means, it would be easier.

up

Could it be that you have vertices that are not used in the triangles?

It could be, but I tried to add one extra vertex to the vertex array and got a different message.

I’d like to know for sure what the error means to be able to find out what causes it. Right now I can’t even reproduce it frequent enough to start debugging.

It’s the opposite, your Triangle Indices have indices > the size of the Vertices array, meaning it’s referencing vertices that could not possibly exist.

I.e. say you had 1000 vertex model. Your Triangles list has an integer greater than 999, which means it’s saying to use a vertex that couldn’t possibly exist.

That’s it, wrong indices in triangles array. Thanks!

You also need to be careful with the order you set triangles and vertices…

If you are removing vertices, you need to update triangles before you update vertices (so you don’t have references to the removed verts).

If you are adding vertices you need to update vertices before triangles.

Or just call Clear() before doing any assignments and make sure you assign everything back again.

True but then you have to rebuild all the arrays.