I have a mesh generation script which initialises a mesh with vertices that represent my map tiles as quads. Then I pass the tiles that I wish to display on the mesh by setting my triangles for the vertices related to the tile.
I was wondering if there is a more optimised way to approach this for Unity. I'm still learning about mesh generation but am unsure if I have designed it efficiently.
This is my initial generation of the mesh before I create any tiles:
private void Awake(){
Generate();
}
private void Generate ()
{
vertices = new Vector3[mapLength * mapWidth * 4];
int v = -1;
for (int j = 0; j < mapLength; j++)
{
for (int i = 0; i < mapWidth; i++)
{
vertices[++v] = new Vector3(i * gridSize, 0, j * gridSize); // bottom left
vertices[++v] = new Vector3(i * gridSize + gridSize, 0, j * gridSize); // bottom right
vertices[++v] = new Vector3(i * gridSize, 0, j * gridSize + gridSize); // top left
vertices[++v] = new Vector3(i * gridSize + gridSize, 0, j * gridSize + gridSize); //top right
}
}
GetComponent<MeshFilter>().mesh = mesh = new Mesh();
mesh.name = "Floor Grid";
mesh.MarkDynamic();
mesh.vertices = vertices;
}
So, now I have created the mesh with the vertices for my quads. I now apply triangles to it when the user wishes to draw tiles I obtain the triangles array and add to it like so:
private void Add(List<Vector3> tiles)
{
int[] triangles;
if (mesh.triangles.Length == 0)
{
// there are currently no tiles so create new array match tile count
triangles = new int[tiles.Count * 6];
}
else
{
// we already have some tiles so expand the existing array
triangles = new int[mesh.triangles.Length + (tiles.Count * 6)];
}
// get the triangle indices from mesh.triangle and apply them to new array
int index = 0;
for (int i = 0; i < mesh.triangles.Length; i++)
{
trianglesList.AddRange(mesh.triangles);
triangles[i] = mesh.triangles[i];
index = i+1;
}
//apply the new triangles for the tiles the user wants
for (int i = 0; i < tiles.Count; i++)
{
tri = (int)(tiles[i].z * mapWidth + tiles[i].x) * 4;
triangles[index++] = tri;
triangles[index++] = tri + 2;
triangles[index++] = tri + 1;
triangles[index++] = tri + 2;
triangles[index++] = tri + 3;
triangles[index++] = tri + 1;
}
mesh.triangles = triangles;
mesh.RecalculateNormals();
}
This code works, but I am no expert at mesh generation and have basically picked up knowledge from others and example scripts over time.
I was wondering if there is any optimising I can do here. Or have I understood how it is done and this is pretty much as good at it gets?