Help with randomly generated terrain!

using UnityEngine;
using System.Collections;

public class Generation : MonoBehaviour {



	void Start () {

		for (int z = 1; z < 20; z++) {
			for (int x = 1; x < 20; x++) {
				//create cube
				GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
				//add rigid body
				cube.AddComponent<Rigidbody>();
				//freze the y axis
				cube.rigidbody.constraints = RigidbodyConstraints.FreezePositionY;
				// create random color
				Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f );
				//color cube
				cube.renderer.material.color = newColor;  
				//create random number to add to y
				int RandomAdd = Random.Range(1,6);
				//create y
				int y = 0;
				//add number to y
				y += RandomAdd;
				//offset
				cube.transform.position = new Vector3(x, y, z);

			}
		}


	}
	

	

	

	void Update () {


	}
}

I am trying to create a game where the cubes randomly generate at random heights, so i can later on place procedural generated building on them, my blocks now do this : Screenshot - eed286ac4c82791fcd6c15edd2b9a46d - Gyazo

I would like them to not have the gaps so it is all connected, how can i do that ?

You’re off to a decent start. At the moment what you are doing is generating a cube at every X/Z position on your grid, and then randomly changing the height. The way i’m envisioning it, you have two options.

1: If you do not want caves to be possible, after you discover the height of your random cube, place an additional cube under it for each step, so at height 3, add another cube at height 0, 1, and 2 at the same X/Z coordinate.

2: If you do want caves, instead of randomly choosing a height, create a third nested loop to cycle through each y location as well. Then randomly determine if you should place a cube at all (you can fiddle with the exact percentage to alter how dense your world will be). To ensure you have no floating cubes, simply keep a list of every place you have placed a cube, then when you are creating a new cube, check to see if there is a cube next to it, and if not and it is not on the lowest level, cancel the placement and skip to the next spot.