Unity Terrain Generation: Using Heightmaps for Level Design

In this post we’ll be creating a Unity editor window that performs some pretty basic Unity terrain generation using a configurable heightmap texture.


Unity’s Terrain class exposes a property called terrainData. TerrainData’s API includes a method called SetHeights, which takes a 2D array of heightmap samples and uses it to deform the surface of it’s parent Terrain object.

Using this as a basis for our implementation, we’ll need to find a way to extract a 2D array of heightmap samples from a heightmap texture.

Extracting Heightmap Samples

A heightmap is a black and white image that stores elevation data. It uses grayscale values, ranging from black to white to represent height, where black is the lowest point and white is the highest point.

We’re going to create a class that’ll be responsible for analyzing heightmaps; let’s call it the HeightmapProcessor.

It’ll loop through the pixels of the heightmap, using 0 to represent black pixels, 1 to represent white pixels, and all the values in between to represent varying shades of gray.

The result will be a 2D array of floats; the extracted heightmap samples.

The Unity Terrain Generation

Now that we’ve got a method of retrieving heightmap samples we can complete the terrain deformer editor window.

The terrain deformer editor window has three configurable properties: a Unity terrain object, a hieghtmap texture, and an integer value that represents the height of the final deformation.

We’ll pass the configured hightmap texture into an instance of the HeightmapProcessor’s GetHeightmapSamples method. Then we’ll take the result and use it to manipulate the Unity terrain object.

The manipulation will include setting the dimensions of the terrain, using the heightmap samples to adjust the width and height, and the configurable height property to set the height value.

Then we’ll take the heightmap samples and pass them into the Terrain.terrainData’s setHeights method.

Find this project on GitHub at