Unity How to Generate Randomized Levels with block/tiles

Attach this example script to your camera or empty GameObject and make sure a “brick_yellow” prefab is in your “Assets/Resources” folder.

PerlinNoise.cs
using UnityEngine;
using System.Collections;
 
public class PerlinNoise : MonoBehaviour {
	void Start () {
		int width = 100;
		int height = 100;
 
		float[,] samples = generatePerlinNoise(width, height);
 
		drawTiles(width, height, samples);
	}
 
	// draw tiles based on samples
	void drawTiles(int width, int height, float[,] samples) {
		float scale = 0.64F; // my prefab uses a 64x64 texture
 
		// loop array
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				float screenX = x * scale;
				float screenY = y * scale;
 
				float tile = samples[x,y];
 
				// 0 is black and 1 is white
				if (tile < 0.45f) {
					continue; // don't draw tiles with blacker values
				} else {
					Instantiate(Resources.Load("brick_yellow"), new Vector2(screenX, screenY), Quaternion.identity);
				}				
			}
		}
	}
 
	// create array with noise samples
	float[,] generatePerlinNoise(int w, int h) {
		float [,] arr = new float[w,h];
		float scale = 1.0F;
 
		Random.seed = (int)System.DateTime.Now.Ticks;
		int seed = Random.Range(0, 99999);
 
		float y = 0.0F;
		while (y < h) {
			float x = 0.0F;
			while (x < w) {
				float xCoord = x / w * scale;
				float yCoord = y / h * scale;
 
				float sample = Mathf.PerlinNoise(xCoord + seed, yCoord + seed);
 
				int indX = Mathf.FloorToInt(x);
				int indY = Mathf.FloorToInt(y);
 
				arr[indX,indY] = sample;
 
				x++;
			}
			y++;
		}
 
		return arr;
	}
}

Sample Output


Navigation
Print/export
Toolbox