Procedural Dungeon Generation in Unity3d

A few years ago I posted a youtube video showing a small tech demo for procedural dungeon generation that I made in unity. Recently, I was asked if I could explain the generation process for it, however I no longer have the code so I figured I could write up a quick blog post to explain it.

Overview of generation process

The process of generation works by taking and spawning an initial "Room" in the world, then checking each doorway to determine other "Rooms" that could possibly match the current door, then spawns a matching room and repeats until there are no more doorways left. This is a bit of an over simplification, but I will go into more detail later.

Prefabs

Each "Room" for the generation is a Unity3d Prefab of a 3d model with holes removed from the model where doorways will be made to connect to other rooms.

Room Connection Diagram

As seen in the diagram above, each door has a connector GameObject associated with it that is attached to the door position. The connector maintains the position information of the door and what type of connector it is. The algorithm determines wether or not two prefabs rooms can connect by comparing the type of connectors. If the connectors match, the rooms are connected. If not,then the most recently placed room is deleted and the door to the original room is sealed with a special "Terminal" prefab. The Terminal prefab is a 3d object that's only job is to seal the hole in the original room so the wall looks like there was never a hole there. This process is repeated until all the spawned rooms no longer have empty connections/are all sealed.

Psuedo code

Control through probability

You can tweak the algorithm to produce much more controllable results by adding probabilities to control the chance of certain rooms connecting with each other. For instance, instead of choosing the first possible room or connector in the psuedo code, you could add probability such that the connector type #2 is choosen 70% of the time before connector #3. This is usefull for when you have something like a boss and treasure room, but you want to ensure that the treasure room is only ever connected after the boss room. You can achieve this, and still resuse connector types, by adding a probability that boss rooms connect to treasure rooms 100% of the time and that any other room has a 0% chance to connect to the treasure room.

I hope this guide has been usefull, if you have any questions please feel free to ask.


Further Resources

Nice list of 2d Dungeon generation Techniques

Procedural Content generation wiki