The current generated effect is as follows
First fill in the height of each grid in excel, a grid occupies a 3*3 position (the color is only used for marking, it has no effect)
Then copy the data in excel to txt, remove the extra carriage return in the last line, I am now like this
Create a map cell type MapCell, which contains 3*3 height attributes: float[,] heights, and its own coordinates Vector2Int posV2 First
read the data of txt and store it in a two-dimensional array mapTextData
TextAsset txt = Resources.Load<TextAsset>(filePath);
string fileText = txt.text;
//替换回车
fileText = fileText.Replace("\r\n", "\n");
string[] fileRows = fileText.Split('\n');
int rowCount = fileRows.Length;
int columnCount = fileRows[0].Split(' ').Length;
mapTextData = new string[rowCount, columnCount];
//读取 txt
for (int i = 0; i < rowCount; i++)
{
string[] currentRow = fileRows[i].Split(' ');
for (int j = 0; j < currentRow.Length; j++)
{
mapTextData[i, j] = currentRow[j];
}
}
Next, create a two-dimensional array of MapCell[,] to record the value of each grid
for (int row = 0; row < 3; row++)
{
for (int column = 0; column < 3; column++)
{
float.TryParse(mapTxtData[i - 1 + row, j - 1 + column], out cellHeights[row, column]);
}
}
Finally, the mesh is generated according to the stored data. The position information of the vertices is the height of the corresponding position in the mapCell. Because each grid is composed of two triangles, the index array of the mesh surface can first record the current number of vertices, and then 0 1 2, 1 3 2 connection
vertices.Add(new Vector3(i, mapCell.heights[0, 0] * gridHeight, j) * mapScale);
vertices.Add(new Vector3(i, mapCell.heights[0, 2] * gridHeight, j + 1) * mapScale);
vertices.Add(new Vector3(i + 1, mapCell.heights[2, 0] * gridHeight, j) * mapScale);
vertices.Add(new Vector3(i + 1, mapCell.heights[2, 2] * gridHeight, j + 1) * mapScale);
//记录mesh索引
indices.Add(currentIndices);
indices.Add(currentIndices + 1);
indices.Add(currentIndices + 2);
indices.Add(currentIndices + 1);
indices.Add(currentIndices + 3);
indices.Add(currentIndices + 2);
When the GameObject is finally generated, you can generate a Cube first, delete its BoxCollider, set the mesh of its MeshFilter to the created mesh, and use the RecalculateNormals that comes with unity to recalculate the normal of the mesh.
Complete project
needs to export fbx, you can use FBX Exporter
Window -> Package Manager to install FBX Exporter