Search code examples
c#unity-game-enginemeshverticestriangle

Half of the triangles of the custom mesh is not created Unity?


I generate a world and record it inside a grid map. Then I draw this map by programmatically drawing a mesh. However when I generate a bigger map half of it is missing. Is there a triangle limit on each mesh or am I doing something wrong?

To demonstrate that my grid isn't faulty, I instantiate a cube for each tile.

50x50 map works fine, but 250x250 doesn't. Custom mesh vs cubes

Here are the relevant methods of this class:

 public void GenerateMesh(Grid3D grid)
{
  
    GameObject blocks = new GameObject("Blocks");
    foreach (Grid3D.Tile tile in grid.GetListOfAllTiles())
    {
       
        if (tile.IsAvailible)
        {
            DrawSurface(tile.GetWorldPosition()); // custom mesh
            Instantiate(testBlock, tile.GetWorldPosition(), Quaternion.identity).transform.parent = blocks.transform ; //cubes for testing
        }
     }

    FinalizeShape(); //convert to array and add the vertice and triangles to the mesh,recalculateNormals, add the material
}

private void DrawSurface(Vector3 p)
{

    AddVertice(0, 0, 0, p);
    AddVertice(0, 0, 1, p);
    AddVertice(1, 0, 0, p);
    AddVertice(1, 0, 1, p);


    int verticeNo = nextVerticeNumber;

    AddTriangle(verticeNo + 0, verticeNo + 1, verticeNo + 2);
    AddTriangle(verticeNo + 1, verticeNo + 3, verticeNo + 2);

    nextVerticeNumber += 4; //each time this method is called new vertices are created. By increasing this we refer to the newly created vertices.
}

private void AddVertice(float offsetX, float offsetY, float offsetZ, Vector3 position)
{
    
    vertices.Add(new Vector3(position.x + offsetX, position.y + offsetY, position.z + offsetZ));

}
private void AddTriangle(int v1, int v2, int v3)
{
    triangles.Add(v1);
    triangles.Add(v2);
    triangles.Add(v3);

}

I can share the rest if needed but I don't want to bloat the post. What I do is this: Read the grid, if a tile is availible get its position. Add some offsets to the position to create the vertices. Create triangles from new vertices. Cache the number of vertices so that then next time DrawSurface method is called I will be able to refer to the new vertices.


Solution

  • By default meshes in Unity are limited to 65536 vertices

    See Mesh.indexFormat

    Index buffer can either be 16 bit (supports up to 65536 vertices in a mesh), or 32 bit (supports up to 4 billion vertices). Default index format is 16 bit, since that takes less memory and bandwidth.

    for more you will need to set the according

    mesh.indexFormat = IndexFormat.UInt32;
    

    Note though

    Note that GPU support for 32 bit indices is not guaranteed on all platforms;