Hi!
I want to generate a tile map in unity and came up with two implementations:
- using a gameobject for each tile
- using MeshFilter, MeshRenderer: Create a submeshes for each tile
I expected that the version using a mesh would be faster than the one using gameobjects, but this was not the case - so I am wondering if I did it correctly (I was reading a tutorial where a big texture was generated by setting pixels and applied to the whole mesh - the author mentioned that using individual vertices for each tile would be more efficient and that it would be easy to apply different textures to each tile - I thought he meant submeshes):
I am generating my tiles using two loops:
Vector3[] vertices = new Vector3[6*hexagonCount];
Vector2[] uv = new Vector2[6*hexagonCount];
List<List<int>> triangles = new List<List<int>>(hexagonCount);
for(int y=0; y<tileNumberY; ++y){
for(int x=0; x<tileNumberX; ++x){
generateHexMesh(ref vertices, ref uv, ref triangles, index, posX, posY, posZ);
}
}
These loops fill my vertices, uv and triangles list/arrays. After that I do the following:
Material[] materials = new Material[hexagonCount];
this.mFilter.mesh.vertices = vertices; //add our vertices to the mesh
this.mFilter.mesh.uv = uv; //add out UV coordinates to the mesh
this.mFilter.renderer.materials = materials;
for(int i=0; i<hexagonCount; ++i){
int[] temp = triangles*.ToArray();*
this.mFilter.mesh.SetTriangles(temp, i);
this.mRenderer.materials = material;
}
this.mFilter.mesh.RecalculateBounds(); //recalcualte the dimensions of our mesh
this.mFilter.mesh.RecalculateNormals();
My code generates the desired Hexagons, but the framerate drops to 5 FPS when running it for 100x100 tiles, while the gameobject version runs at 300 FPS. Did I do something wrong or are submeshed not meant to be used in such ways? How are submeshes used correctly to be able to assign different textures to those tiles?
EDIT: Updated code according to robertbu’s suggestions
this.mFilter.mesh.vertices = vertices; //add our vertices to the mesh
this.mFilter.mesh.uv = uv; //add out UV coordinates to the mesh
for(int i=0; i<hexagonCount; ++i){
this.mFilter.mesh.SetTriangles(triangles*.ToArray(), i);*
}
this.mRenderer.material = material;
this.mFilter.mesh.RecalculateBounds(); //recalcualte the dimensions of our mesh
this.mFilter.mesh.RecalculateNormals();
UVS used for each hexagon:
// generate uv
Vector2[] uv = new Vector2[]{
new Vector2(0,0.25f),
new Vector2(0,0.75f),
*new Vector2(0.5f,1), *
new Vector2(1,0.75f),
new Vector2(1,0.25f),
*new Vector2(0.5f,0), *
};