Hello, for a while now I’ve been trying to make my planet surface generation script(as in a planet with bumps and mountains) but so far all I managed to do is to generate a customizable “cube sphere” type of object like the one in this tutorial. Now that I have a spherical mesh I’m trying to add a heightmap to its surface to add some surface variations but the problem is - my code doesn’t work(at least not as intentioned). I can’t figure out what’s the issue with it, there is no error in runtime and when I try to change things and press play the entire editor crashes.

I have made a ConvertHeightToMesh function which is supposed to take an inputted heightmap and turn it into a physical terrain on the surface of the cube sphere. Here it is:

```
private Mesh mesh;
private Vector3[] vertices; // cube sphere vertices
private Vector3[] normals; // cube sphere normals
private Color32[] cubeUV; // currently displays red green blue colors to help differentiate faces
public Texture2D hMap; // HeightMap received from input
```

```
void ConvertHeightToMesh()
{
List<int> triangles = new List<int>();
int hWidth = hMap.width;
int hHeight = hMap.height;
//Bottom left section of the map, other sections are similar
for (int i = 0; i <= hWidth; i++)
{
for (int j = 0; j <= hHeight; j++)
{
//Add each new vertex in the plane
vertices[i] += (new Vector3(i, hMap.GetPixel(i, j).grayscale * 100, j));
//Skip if a new square on the plane hasn't been formed
if (i == 0 || j == 0) continue;
//Adds the index of the three vertices in order to make up each of the two tris
triangles.Add(250 * i + j); //Top right
triangles.Add(250 * i + j - 1); //Bottom right
triangles.Add(250 * (i - 1) + j - 1); //Bottom left - First triangle
triangles.Add(250 * (i - 1) + j - 1); //Bottom left
triangles.Add(250 * (i - 1) + j); //Top left
triangles.Add(250 * i + j); //Top right - Second triangle
}
}
Vector2[] uvs = new Vector2[vertices.Length];
for (var i = 0; i < uvs.Length; i++) //Give UV coords X,Z world coords
uvs[i] = new Vector2(vertices[i].x, vertices[i].z);
mesh.vertices = vertices; //Assign verts, uvs, and tris to the mesh
mesh.uv = uvs;
// Add heightmap triangles to surface triangles
for(int i = 0; i < mesh.triangles.Length; i++)
{
mesh.triangles[i] += triangles[i];
}
mesh.RecalculateNormals(); //Determines which way the triangles are facing
}
```

The problem is I can’t get the calculations correctly and its very hard to do trial and error when the editor keeps crashing all the time. This is the latest result I have gotten when pressing play without it crashing:

How would I go about doing this correctly? I’m really lost in the calculations and have read many articles about it.