How to create random levels with Unity 3D

Mihails Tumkins
3 min readMay 29, 2019

--

Today I want to look into one approach to generate random levels in Unity.

Here you can play with the final result:

Let’s get started.

I’ll explain what we will be doing and then you can look at the code yourself, to do so — just clone the project from https://github.com/mihailt/LevelGeneration and dig in.

The entire project is made using Unity3d 2019.1.0f2, Cinemachine 2.3.4, TextMeshPro 2.0.1

To generate our dungeon we will be using a variation of Random Walk algorithm called Drunkard Walk.

In this algorithm, a walker is placed on the grid and then it moves in one of the predefined directions in a random manner. Then we remember all the positions walker has visited and render floor tiles onto it.

First, we define a grid and mark all tiles as empty, then we add one walker and see what happens.

This already can give us interesting results, for instance, 100 steps on a 30x30 grid will give us something like this:

But we can improve this result by adding some variation to it. We can start from one walker, and then on each step introduce a chance to spawn or destroy one walker.

For instance 10 walkers maximum on the same 30x30 grid will provide something like this:

which looks much more natural than previous results.

So now next step is to generate walls, to do that all we need to do is to iterate through each tile in the grid see if it is floor and then replace all empty tiles around it with wall tiles

Optionally we can replace every wall tile above ground tile and every wall above empty tile to a wall tile with decoration to achieve a better look.

Now we can add player and exit to the level to walk around it.

Usually while not necessary I add a player to the first walker initial position and then iterate through all floor tiles check the distance between player and tile and place the exit on the furthest tile.

And now let us look at the final result.

Basically, our map generator is almost done at this point.
We can start adding player, enemies, items, etc…

Suggestions:

I would suggest for you to experiment with the provided demo.
You could provide different probabilities for walker spawning, turning and destroying. Then you can add items and enemy spawning rules based on those variables. Also if you’re someone like me you probably don’t like those occasional single wall tile blocks, so you could go ahead and implement their removal.

Have fun! ))

--

--