So I have this script for terrain generation like minecraft, but when I attach the script to a cube and press generate when running, it takes a couple of seconds for the terrain to load in. That is fine for me, but it creates the whole terrain at the same time. How can I code it so then it like creates line per line or block per block, but at a constant speed, because I don’t want to wait like 30 seconds for a 500 by 500 terrain to generate, I want to see it creating the terrain piece by piece. I know I need to change the for loop in the script somehow. Here is the script, TYVM!
using UnityEngine;
using System.Collections;
public class Blocks : MonoBehaviour
{
//Public variable for the size of the terrain, width and heigth
public Vector2 TerrainSize = new Vector2( 50 , 50 );
//Height multiplies the final noise output
public float HeightOfTerrain = 10.0f;
//This divides the noise frequency
//Higher is Flatter
public float NoiseSize = 10.0f;
private GameObject root;
void OnGUI ()
{
//Make a button that calls generate function when you press it
//(left, top, width, height), "name"
if(GUI.Button( new Rect( 10, 10, 100, 30 ), "Generate" ))
{
//Call the generate function
Generate();
}
}
//Function that inputs the position and spits out a float value based on the perlin noise
public float PerlinNoise(float x, float y)
{
//Generate a value from the given position, position is divided to make the noise more frequent.
float noise = Mathf.PerlinNoise( x / NoiseSize, y / NoiseSize );
//Return the noise value
return noise * HeightOfTerrain;;
}
//Generates the terrain
void Generate ()
{
//Destroy the current terrain if there is one
Destroy(GameObject.Find("Terrain"));
//Create a new empty gameobject that will store all the objects spawned for extra neatness
root = new GameObject("Terrain");
//Put the root object at the center of the boxes
root.transform.position = new Vector3( TerrainSize.x/2, 0, TerrainSize.y/2 );
//For loop for x-axis (width)
for(int i = 0; i <= TerrainSize.x; i++)
{
//For loop for z-axis (length)
for(int p = 0; p <= TerrainSize.y; p++)
{
GameObject box = GameObject.CreatePrimitive(PrimitiveType.Cube);
box.transform.position = new Vector3( i, PerlinNoise( i, p ), p);
box.transform.parent = root.transform;
}
}
//Move the root at the origin.
root.transform.position = Vector3.zero;
}
}