Documentation / API Reference

Dungeon API Reference

The source-verified public API of the Procedural Dungeon Generator in namespace DungeonGen: the generation managers, the decorator, rendering and geometry contracts, post-processing and culling, and the authoring ScriptableObjects.

namespace DungeonGensource-verifiedUnity 6
Dungeon Generator template graph with connected entrance, room, treasure and boss nodes in Unity
Template graphSource-verified
01 / Map

Namespace overview

Everything public lives in namespace DungeonGen:

AreaTypes
Assembly runtimeDungeonManager, RoomDecorator, ChunkDungeonStreamer, ChunkStreamer, ChunkPlanner, ChunkMaterializer, ChunkRoomProviderFactory
RenderingIDungeonRenderer, PrefabDungeonRenderer, DungeonTheme
Post-processing & cullingIDungeonPostProcessor, IDungeonPreClearProcessor, DungeonPostProcessor, DungeonPostProcessContext, DungeonNavMeshPostProcessor, DungeonCulling, ICullConnectionRule, ICullRoomRule
Authoring assetsDungeonTemplate, RoomDesign, DecorationProfile, DoorSocketType, ProgressionRequirement
Geometry & coreIRoomGeometry, RoomData, DoorSocket, RoomType, TileType, GeneratedRoomInfo, DungeonObjectPool, DungeonData, DungeonConfig
02 / Core assembly

DungeonManager

DungeonManager : MonoBehaviour plans a complete DungeonTemplate tree in pure math, then materializes it transactionally — previous output is only cleared after a successful plan. Exposed in the inspector as a Generate Dungeon button and as the context menu Generate Dungeon.

Methods

MemberDescription
void Generate()Validates the template, plans (managed or optional Burst planner), materializes, wires sockets, places progression items, decorates, and runs post-processors. Rejects overlapping generation.
void ClearAllChildren()Clears generated rooms and the spawned prototype player; deferred automatically while generation is running.
void AddNavMeshSupport()Idempotent convenience action: attaches DungeonNavMeshPostProcessor (which auto-adds DungeonNavMeshSurfaceHost + NavMeshSurface).
void AddCullingSupport()Idempotent convenience action: attaches DungeonCulling for additive portal culling.

Key fields

FieldPurpose
template (DungeonTemplate)Mandatory — generation aborts without it.
roomPool (List<RoomPoolEntry>)Weighted random candidates: prefab, weight, allowedContexts.
generationModeDungeonGenerationMode: TemplateExact or TemplateSequencedRandom.
seed / useRandomSeedFixed or random seed for deterministic generation.
seamPadding / allowedSeamOverlapExtra space kept between adjacent rooms; allowed overlap at a seam.
maxSearchNodesMaximum placement attempts before planning gives up.
allowRotationAllow 90° room rotation to fit socket directions.
root (Transform)Parent transform for instantiated rooms; null = this transform.
sceneEntrance (RoomData)Optional pre-placed scene anchor used as the dungeon's root.
decorateAfterGenerationRun RoomDecorator on each room after generation.
useBurstPlanner / addRandomBranchesInExactOptional Burst planner; random branches in exact mode.

Supporting types: DungeonGenerationMode (TemplateExact = 0, TemplateSequencedRandom = 1); RoomPlacementContext ([Flags]: Template, SequenceFiller, RandomBranch, All); RoomPoolEntry (struct with Allows(context)); RoomType (Normal, Entrance, Exit, Treasure, Boss).

03 / Chunk streaming

ChunkDungeonStreamer

ChunkDungeonStreamer : MonoBehaviour is the scene-facing chunk streamer: it measures the assigned prefabs, plans a (2·plannedRadius+1)² neighborhood and materializes a (2·loadedRadius+1)² neighborhood around the player. The initial load settles synchronously so the player spawns into a ready world; later center changes are frame-sliced. Chunk instances pool on a sibling ChunkPool container, and unloaded chunk roots stay inactive for cheap revisits.

Methods

MemberDescription
bool Initialize()Measures all prefabs, builds the streamer, and settles the initial loaded neighborhood. Idempotent; inspector button Generate World / context menu Generate World. Returns false with a clear log on invalid configuration.
bool UpdateCenterFromPlayer()Re-centers the streamed world on the player's current chunk. Idempotent while the player stays in the same chunk. Button Recenter on Player.
ChunkCoord CenterFromPosition(Vector3 position)Chunk coordinate for a world position (floor division, Floor = 0).
void Dispose()Releases all loaded chunks, the spawned player, and the pool. Button Clear World.
void Rebuild()Dispose() then Initialize() — clears the world and generates it again. Button Rebuild World.
static int ChunkSizeMinimum(int maxRoomWidth, int maxRoomHeight, int safetyMarginCells)Geometry gate: 3× the largest room side plus 2× the safety margin (cells per side).
static int ChunkSizeRecommended(int maxRoomWidth, int maxRoomHeight, int safetyMarginCells)Minimum + MainPathWidthCells (2) for corridor breathing room.

Key fields

FieldPurpose
player / playerPrefabStreaming center transform, or a prefab spawned at the entry room in Play Mode.
corridorPrefabMandatory 1×1 corridor module with one cardinal DoorSocket per direction — no procedural fallback.
useDedicatedEntry / entryPrefabsDedicated entry room prefabs for the first room of every chunk; off = pool-only mode.
roomPrefabs / minRooms / maxRoomsPool prefabs (measured automatically) and the per-chunk room-count range.
cellsPerSide / cellSizeChunk dimensions in cells and world size per cell (must match the room grid).
plannedRadius / loadedRadiusPlanned and instantiated neighborhood radii (loadedRadius ≤ plannedRadius).
worldSeed / useRandomSeed / keyPrefabDeterministic world seed; optional universal key prefab for locked worlds.

Supporting chunk architecture

These types back the streamer and are part of the public DungeonGen namespace: ChunkStreamer (load/unload scheduling, Dispose(), LoadedCount, LastError), ChunkPlanner (deterministic chunk layouts, Plan(...), ChunkPlanResult, ChunkPlanStatus/ChunkPlanFailureKind), ChunkMaterializer (room and corridor instantiation), ChunkRoomProviderFactory (Measure(prefab, cellSize, out provider, out error)), ChunkGridSettings (chunk dimensions, room limits, streaming distance, IsValid(out error)), ChunkCoord (X, Z, Floor, Zero, ToKey()), ChunkKeyPickup, and ChunkRoomRequiresKey.

04 / Decoration

RoomDecorator

RoomDecorator fills a room from a DecorationProfile. The same solver runs in the editor preview and at runtime; runtime prefabs can use RoomDecorationAuthoring, which stores a baked geometry snapshot from the room design.

Constructors: RoomDecorator(RoomDesign design, Transform root, DecorationProfile profile, int seed) and RoomDecorator(IRoomGeometry geo, Transform root, DecorationProfile profile, int seed).

MemberDescription
DecorationResult DecorateAll()Clears previous placement, then solves every category in priority order.
DecorationResult DecorateCategory(string categoryId)Re-solves a single category (removes its previous instances first).
void DespawnCategory(string categoryId)Removes one category's instances.
void DespawnAll()Removes all instances (pool-aware).
IReadOnlyList<PlacedInstance> PlacedCurrent placements.

Result types: DecorationResult (placed, diagnostics, hasErrors, errorMessage), PlacedInstance (instance, categoryId, categoryName, worldPosition, worldRotation, footprint, boundsSize, padding, floor, gridX, gridY, prefab, occupancy), and GroupDiagnostic (targetCount, placedCount, candidateCount, solveMilliseconds, instantiateMilliseconds, groupDead, groupDeadReason, rejectionCounts).

Authoring enums: PlacementSurface, PlacementRegion, AmountMode, FailurePolicy, WallRegion, OccupancyMode, DistributionMode, OrientationMode, RelationType, FloorScope, and FitMode.

05 / Contracts

Rendering & room geometry

IDungeonRenderer

MemberSignature
Rendervoid Render(DungeonData data, DungeonTheme theme, Transform root)
Clearvoid Clear(Transform root)
PlaceCeilingsvoid PlaceCeilings(DungeonData data, DungeonTheme theme, Transform root)

The default implementation is PrefabDungeonRenderer. Implement or wrap IDungeonRenderer to swap the rendering backend.

IRoomGeometry

Geometry contract for the decorator, implemented by RoomDesign (editor) and RoomDecorationAuthoring (runtime baked snapshot); RoomDesignGeometry is the adapter struct. Members: Width, Height, FloorIndices (IReadOnlyList<int>), TileSize, FloorHeight, WallThickness, CenterPivot; TileType[] GetFloor(int floor), InBounds(x, y), IsWallAt(x, y, floor), HasDoorAt(x, y, floor), IsStairFloorOpeningAt(x, y, floor), IsStairCeilingOpeningAt(x, y, floor), IsInStairFootprint(StairPlacement, x, y), Doors, and Stairs.

06 / After generation

Post-processing & culling

Post-processing contracts

  • IDungeonPostProcessorint Priority { get; } and void Process(DungeonPostProcessContext context). DungeonManager runs every enabled processor on its GameObject after materialization, wiring, progression, and decoration; higher Priority first, stable on ties.
  • DungeonPostProcessor — abstract MonoBehaviour carrier with a serialized priority, so processors can be added as components without code.
  • DungeonPostProcessContext — read-only per-run snapshot: RunSeed, Root, Rooms, LayoutRooms, Connections; valid for the duration of Process.
  • IDungeonPreClearProcessorvoid BeforeClear(), invoked at the start of the manager's clear so processors can release references to rooms that are about to be destroyed (for example a baked NavMesh).

DungeonNavMeshPostProcessor

Implements both post-processor contracts and bakes one whole-dungeon NavMesh per generation. Key fields: agentTypeID, buildOnProcess, useDoorLinks, bakeConnectors, logErrors. Requires DungeonNavMeshSurfaceHost (auto-added with the surface).

DungeonCulling and rules

DungeonCulling is an additive portal-culling post-processor: it reads the generated room graph and socket state and only toggles renderer/activation state — removing the component restores the exact unculled behavior. Mode: DungeonCullingMode (Disabled, DisableRenderers, DeactivateRooms). Key members: Refresh(), PollNow(), IsRoomVisible(RoomData), SetConnectionRule(ICullConnectionRule), AddRoomRule(ICullRoomRule), RemoveRoomRule(ICullRoomRule), SetReference(Transform), plus toggles such as UseDoorState, UseMaxHops, UseOcclusionTolerance, UseDistanceCulling, UseVisibleRoomBudget, MaxHops, and MaxVisibleRooms.

ContractPurpose
ICullConnectionRulebool IsPassable(DungeonConnectionInfo connection)Decides whether a wired connection is passable for the visibility BFS. Default: DoorSocketRule (passable iff both sockets are open and unlocked).
ICullRoomRulebool? OverrideVisibility(RoomData room)Optional per-room override layered on the BFS result; the first registered rule that returns a value wins.
07 / Authoring

Authoring ScriptableObjects

All assets are created via Assets ▸ Create ▸ DungeonGen ▸ …:

AssetKey members
RoomDesign
(Room Design)
roomType, width, height, activeFloor, doors, stairs, theme, decorationProfile, decorationSeed; GetFloor(int), InBounds, IsWallAt, HasDoorAt, IsStairFloorOpeningAt, IsStairCeilingOpeningAt, HasFloor/AddFloor/RemoveFloor, Floors; structs FloorTiles, StairPlacement, DoorPlacement.
DungeonTemplate
(Dungeon Template)
nodes, edges, rootNodeId; FindNode(id), FindEdge(from, to), DefaultColor(RoomType); TemplateNode (id, type, pinnedPrefab, providedRequirements, graphPos) and TemplateEdge (id, fromNode, toNode, requirement).
DungeonTheme
(DungeonTheme)
tileSize, floorHeight, wallThickness, pivot (Corner/Center), prefabs (list of TilePrefab: prefab, sizeX, sizeY, canRotate), stairProfile (StairProfile: assembly mode, pieces, length, backLength, width), ResolveStairProfile().
DecorationProfile
(Decoration Profile)
categories; FindCategory(id), GetSortedByPriority(); each DecorationCategory carries surface, region, pool, footprint, relations, and failure policy configuration.
DoorSocketType
(Door Socket Type)
DisplayName, Color, CompatibleTypes, SetCompatibleType(other, bool), HasCompatibleType(other), IsCompatibleWith(other). Untyped sockets are wildcards; typed sockets match by asset identity or authored compatibility.
ProgressionRequirement
(Progression Requirement)
StableId, DisplayName, DefaultItemPrefab. Gates template edges and locks connections until fulfilled.
08 / Lock & key

Progression contracts

  • IItemSpawnPointbool CanSpawn(ProgressionRequirement requirement) and bool TrySpawn(ItemSpawnRequest request). Default MonoBehaviour implementation: ItemSpawnPoint (optional target and prefab override).
  • ItemSpawnRequest — readonly struct (requirement, roomRoot).
  • ProgressionItemToken — MonoBehaviour stamped on spawned items (Requirement, Configure(requirement)).
  • IConnectionGateProgressionRequirement Requirement, bool IsLocked, CanHandle(requirement), Configure(requirement), Unlock(). Default implementation: BasicConnectionGate.

ProgressionRequirement assets gate template edges; a gate holds the connection until the requirement is fulfilled, and item spawn points place the items that fulfill it.

09 / Foundation

Supporting core types

TypeRole
RoomData (MonoBehaviour)Root component on room prefabs: width, height, tileSize, EffectiveTileSize, roomType, doorSockets; TryGetOrderedSockets(out, out), FindSocket(gridX, gridY), CloseAllDoors(), OpenDoor(IDoorSocket), OpenDoorAt(gridX, gridY), Sockets.
DoorSocket (MonoBehaviour)Visual and logical doorway state (open, closed, passage, locked) with IsOpen/IsLocked, state setters such as SetOpen(bool), SetLocked, SetPassage, and ShowConnectorVisual; DoorSocketType compatibility; ChunkSocketRole for chunk seams.
RoomType / TileTypeRoom roles (Normal, Entrance, Exit, Treasure, Boss) and grid cell types (Empty, Floor, Wall, Door, CorridorFloor, CorridorWall, Hole, Ceiling).
GeneratedRoomInfo (MonoBehaviour)Marker component on generated room roots; carries the room origin and is used by the manager's cleanup sweep.
DungeonObjectPool (MonoBehaviour)Runtime pooling for room and decoration prefabs.
DungeonData / DungeonConfigCore data containers feeding the renderer and the generation pipeline.
HelpersCorridor, Direction, Vec2Int, DoorConnectionResolver, DungeonTemplateValidator, DungeonTemplateGraph — connection matching, validation, and graph helpers.

See also Dungeon Quick Start for the practical flow and Dungeon Generator Overview for the authoring/assembly model.

Back to top ↑