目前生成的效果如下
首先在excel中填写每个格子的高度,一个格子占3*3的位置(颜色只是用来标志的,没有作用)
然后把excel中的数据复制到txt中,去掉最后一行多余的回车,我这现在是这样的
创建一个地图单元格的类型MapCell,里面包含3*3的高度属性: float[,] heights,以及自身坐标Vector2Int posV2
首先读取txt的数据,存入一个二维数组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];
}
}
接下来创建一个MapCell[,] 的二维数组,记录每个格子的值
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]);
}
}
最后根据储存的数据生成mesh,vertices顶点的位置信息就是mapCell里的对应位置的高度,因为个格子都是由两个三角形组成,所以网格面的索引的数组可以先记录当前的顶点数,然后0 1 2,1 3 2连接
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);
最后生成GameObject的时候,可以先生成一个Cube,删除他的BoxCollider,把他MeshFilter的mesh设置成创建的mesh,并且使用unity自带的RecalculateNormals重新计算mesh的法线。
完整工程
需要导出fbx可以用FBX Exporter
Window -> Package Manager里安装FBX Exporter