I am generating a tilemap on a mesh by making new vertices, triangles and uv maps to a mesh.
However I'd like to update the mesh whilst playing the game, like changing a tile texture for example.
I have a way of doing this but it feels like there is a much better way to do so, which is less of a hassle on the system. Here is my way, any thoughts on how I could optimize this?
private int squareCount;
private float tUnit = 0.125f;
private List objVertices = new List();
private List objTriangles = new List();
private List objUV = new List();
void GenObjMesh(int x, int y, Vector2 texture)
{
objVertices.Add(new Vector3(x, y, 0));
objVertices.Add(new Vector3(x + 1, y, 0));
objVertices.Add(new Vector3(x + 1, y - 1, 0));
objVertices.Add(new Vector3(x, y - 1, 0));
objTriangles.Add(squareCount * 4);
objTriangles.Add((squareCount * 4) + 1);
objTriangles.Add((squareCount * 4) + 3);
objTriangles.Add((squareCount * 4) + 1);
objTriangles.Add((squareCount * 4) + 2);
objTriangles.Add((squareCount * 4) + 3);
objUV.Add(new Vector2(tUnit * texture.x, tUnit * texture.y + tUnit));
objUV.Add(new Vector2(tUnit * texture.x + tUnit, tUnit * texture.y + tUnit));
objUV.Add(new Vector2(tUnit * texture.x + tUnit, tUnit * texture.y));
objUV.Add(new Vector2(tUnit * texture.x, tUnit * texture.y));
squareCount++;
}
public void changeObjData(int[,] mapToChange, float x, float y , int obj)
{
x = Mathf.FloorToInt(x);
y = Mathf.CeilToInt(y);
mapToChange[(int)x, (int)y] = obj; //set info for buildmesh()
objVertices.Clear();
objTriangles.Clear();
objUV.Clear();
squareCount = 0;
GenObjMesh((int)x, (int)y, new Vector2(7, 6)); //new texture
BuildMesh(); //generate map with new info
}
void UpMesh()
{
objMesh.Clear();
objMesh.vertices = objVertices.ToArray();
objMesh.triangles = objTriangles.ToArray();
objMesh.uv = objUV.ToArray();
objMesh.Optimize();
objMesh.RecalculateNormals();
}
//buildmesh() just gathers data to form the entire mesh
The problem with this is that it rebuilds the entire mesh, instead of one object/tile. Any ideas?
↧