World Generation Instantiate Slowly

I have been working on some random world generation using cubes and my code has gotten to a slightly working stage. It generates a minecraftesque looking area but my problem is it instantiates 1 cube at a time through a loop.

As you can probably tell, this would be pretty slow. I was wondering if there would be a faster way to generate all the cubes instead of just instantiating 1 at a time?

I will post my ugly code below so you can get a slight idea of how it works (hopefully)

Sorry I explained this so badly but its kinda hard to explain.

    #pragma strict
var prefab : GameObject;
var dirt : GameObject;
var stone : GameObject;
var dirtstone : int;
var objectPos : Transform;
var chance : int;
static var objectcount : int;
var minObjectHeight : int;
var maxObjectHeight : int;
static var generationtime : int = 500;
var lastHeight : int;

function Start () {
objectPos.position.x = 0;
objectPos.position.y = 3;
objectPos.position.z = 0;
minObjectHeight = 1;


}

function Update () {

for (objectcount = 0; objectcount < 4000; objectcount++)
{
dirtstone = Random.Range (1,3);

if (dirtstone == 1){
prefab = dirt;
}

if (dirtstone == 2){
prefab = stone;
}

if (generationtime >0)
{
maxObjectHeight = Random.Range (100,105);
generationtime -= 1;



chance = Random.Range (1, 3);

if (chance == 2)
	{
		
		objectcount += 1;
		GameObject.Find("g_Health").guiText.text

= “”+objectcount;

for (objectPos.position.y = 0; objectPos.position.y <

maxObjectHeight; minObjectHeight++)
{

objectPos.position.y = minObjectHeight;
prefab = Instantiate(prefab, objectPos.position,

objectPos.rotation);
}

if (objectPos.position.y > maxObjectHeight)
{
minObjectHeight = 1;
objectPos.position.y = minObjectHeight;

if (objectPos.position.x >= 16)
{
objectPos.position.z += 1;
objectPos.position.x = 0;
}

else

objectPos.position.x += 1;

			
}
}
}
}
}

Don’t use Update, just use a normal function, and loop through all the objects at once. Although using individual cubes is very slow and inefficient compared to building an optimal mesh.

I recently had to do something very similar…

What you really need to do is work toward getting your generation functionality into an Editor Script, so you can pick an option off the menu to “Generate Map”.

Then, you’ll have your scene all ready to go, with all that slow map creation process done pre-runtime.