Rudimentary Stitch Unity Terrain

I’ve added a rudimentary terrain stitch function to the project in the Split Terrain post. It will take the top neighbor and match their bottom edge to our top edge, and it will take our left neighbor and match their right edge to our left one.

void stitchTerrain(GameObject center, GameObject left, GameObject top)
{
    if (center == null)
        return;
    Terrain centerTerrain = center.GetComponent<Terrain>();
    float[,] centerHeights = centerTerrain.terrainData.GetHeights(0, 0, centerTerrain.terrainData.heightmapWidth, centerTerrain.terrainData.heightmapHeight);
    if (top != null)
    {
        Terrain topTerrain = top.GetComponent<Terrain>();
        float[,] topHeights = topTerrain.terrainData.GetHeights(0, 0, topTerrain.terrainData.heightmapWidth, topTerrain.terrainData.heightmapHeight);
        if (topHeights.GetLength(0) != centerHeights.GetLength(0))
        {
            Debug.Log("Terrain sizes must be equal");
            return;
        }
        for (int i = 0; i < centerHeights.GetLength(1); i++)
        {
            centerHeights[centerHeights.GetLength(0) - 1, i] = topHeights[0, i];
        }
    }
    if (left != null)
    {
        Terrain leftTerrain = left.GetComponent<Terrain>();
        float[,] leftHeights = leftTerrain.terrainData.GetHeights(0, 0, leftTerrain.terrainData.heightmapWidth, leftTerrain.terrainData.heightmapHeight);
        if (leftHeights.GetLength(0) != centerHeights.GetLength(0))
        {
            Debug.Log("Terrain sizes must be equal");
            return;
        }
        for (int i = 0; i < centerHeights.GetLength(0); i++)
        {
            centerHeights[i, 0] = leftHeights[i, leftHeights.GetLength(1) - 1];
        }
    }
    centerTerrain.terrainData.SetHeights(0, 0, centerHeights);
}

We run this function on each of our terrain pieces after breaking apart our original terrain.