Reference
Dungeon API Reference
The public API of Easy Dungeon Generator 1.1.0, in namespace DungeonGen. It covers the managers, decoration, rendering and geometry contracts, post-processing and culling, and the authoring assets. For how to use these in a project, read the guides.
On this page
- Namespace overview
- DungeonManager
- Methods
- Status and events
- Serialized fields
- ChunkDungeonStreamer
- Methods
- State and events
- Serialized fields
- Supporting chunk types
- RoomDecorator and RoomDecorationAuthoring
- RoomDecorationAuthoring
- Rendering and room geometry
- IDungeonRenderer
- IRoomGeometry
- Post-processing and culling
- Post-processing contracts
- DungeonNavMeshPostProcessor
- DungeonCulling and rules
- Authoring ScriptableObjects
- Progression contracts
- Supporting core types
Namespace overview#
| Area | Types |
|---|---|
| Generation | DungeonManager, ChunkDungeonStreamer, ChunkStreamer, ChunkPlanner, ChunkMaterializer, ChunkRoomProviderFactory, RoomDecorator, RoomDecorationAuthoring |
| Rendering | IDungeonRenderer, PrefabDungeonRenderer, DungeonTheme |
| Post-processing and culling | IDungeonPostProcessor, IDungeonPreClearProcessor, DungeonPostProcessor, DungeonPostProcessContext, DungeonNavMeshPostProcessor, DungeonNavMeshSurfaceHost, DungeonCulling, ICullConnectionRule, ICullRoomRule, DoorSocketRule |
| Authoring assets | RoomDesign, DungeonTemplate, DecorationProfile, DoorSocketType, ProgressionRequirement |
| Geometry and core | IRoomGeometry, RoomData, DoorSocket, GeneratedRoomInfo, DungeonObjectPool, DungeonData, DungeonConfig |
| Progression | IItemSpawnPoint, ItemSpawnPoint, ItemSpawnRequest, IConnectionGate, BasicConnectionGate, ProgressionItemToken |
| Enums | DungeonGenerationMode, SeamMode, DungeonGenerationStatus, RoomPlacementContext, RoomType, TileType, DungeonCullingMode, ChunkSocketRole, Direction |
DungeonManager#
DungeonManager : MonoBehaviour plans the whole DungeonTemplate first and only then replaces the previous output. Generation is rejected while a run is in progress.
Methods#
| Member | Description |
|---|---|
void Generate() | Validates the template, plans, materializes the rooms, wires the doors, places progression items, decorates, and runs the post-processors. Also the inspector button Generate Dungeon and the context menu Generate Dungeon. |
void ClearAllChildren() | Removes the generated rooms and the spawned prototype player. Deferred until the current generation step ends. |
void PrewarmForGeneration() | Measures the room prefabs and fills the object pool in advance. Safe to call repeatedly; Generate() calls it too. |
void AddNavMeshSupport() | Adds DungeonNavMeshPostProcessor, with its DungeonNavMeshSurfaceHost and a NavMeshSurface. Does nothing when it is already present. |
void AddCullingSupport() | Adds DungeonCulling. Does nothing when it is already present. The mode stays Disabled until you set it. |
Status and events#
StatusDungeonGenerationStatus read-only- State of the latest run:
Idle,Generating,Ready,Failed, orCancelled. A failed run keeps the previous dungeon. IsGeneratingbool read-only- True while
StatusisGenerating. GenerationProgressfloat read-only, 0 to 1- Progress of the current run.
StatusChangedevent Action<DungeonGenerationStatus>- Raised with the new status each time it changes.
Serialized fields#
The inspector shows these fields under its section names. The guide DungeonManager settings describes each one.
templateDungeonTemplate required- Generation stops with an error when it is empty.
generationModeDungeonGenerationMode default TemplateExactTemplateExact(0) orTemplateSequencedRandom(1).useBurstPlanner,addRandomBranchesInExactbool default off- Burst planner, and random branches in exact mode.
roomPoolList<RoomPoolEntry>- Weighted candidates:
prefab,weight(minimum 0; the constructor default is 1), andallowedContexts. An empty context value means all contexts. maxSearchNodesint default 10000, minimum 100- Placement attempts before the planner gives up.
allowRotationbool default on- Allows 90° steps to match socket directions.
mainPathRoomCount,minOffshootSequenceFillers,maxOffshootSequenceFillers,maxRandomBranchRooms,minRandomBranchStarts,maxRandomBranchStarts,allowRandomSubbranches,maxRandomBranchDepthint, bool- Sequenced random tuning. Defaults: 10, 0, 2, 10, 1, 1, on, 4.
seedint default 0,useRandomSeedbool default on- The seed is used when
useRandomSeedis off. seamPadding,allowedSeamOverlapfloat default 0 and 0- Space kept between adjacent rooms, and the overlap allowed at a seam.
wallModeSeamMode default SingleOnlySingleOnly(0),DoubleOnly(1), orAllowBoth(2). See Wall mode.rootTransform null = this transform- Parent for the instantiated rooms.
sceneEntranceRoomData- Optional room placed in the scene, used as the root of the dungeon.
useEntranceSeamPadding,entranceSeamPaddingbool, float default off and 0- Seam padding for the rooms attached directly to
sceneEntrance. prototypePlayerPrefab,spawnPrototypePlayerGameObject, bool empty and on- Player spawned at the entrance in Play Mode after generation.
generationFramesint default 1,generationFrameBudgetMsfloat default 0- Frames over which generation is spread in Play Mode, and the millisecond budget per frame. A budget of 0 turns it off.
roomPoolPrewarm,decorationPoolPrewarmint default 5 and 20- Pre-created copies of each room and decoration prefab.
prewarmOnAwakebool default on- Runs
PrewarmForGenerationinAwake. maxPlanRetriesint default 50,planRetryTimeoutMsint default 2000- Retries with a new seed when rooms do not fit, and the time limit for all retries.
decorateAfterGenerationbool default on- Decorates each room that has a
RoomDecorationAuthoring. logGeneration,logDecorationDiagnosticsbool default off- Informational log output. Errors and warnings are always logged.
Supporting types: DungeonGenerationMode (TemplateExact = 0, TemplateSequencedRandom = 1); SeamMode (SingleOnly = 0, DoubleOnly = 1, AllowBoth = 2); DungeonGenerationStatus (Idle = 0, Generating = 1, Ready = 2, Failed = 3, Cancelled = 4); RoomPlacementContext ([Flags]: Template, SequenceFiller, RandomBranch, All); RoomPoolEntry (struct with Allows(context)); RoomType (Normal, Entrance, Exit, Treasure, Boss).
ChunkDungeonStreamer#
ChunkDungeonStreamer : MonoBehaviour plans a (2·plannedRadius+1)² area of chunks around the player and builds a (2·loadedRadius+1)² area. The initial load completes in one call, so the player spawns into a finished world. Later moves are spread over frames. Unloaded chunks stay inactive in a pool and are reused.
Methods#
| Member | Description |
|---|---|
bool Initialize() | Measures the prefabs and builds the initial area. Returns false, and logs why, when the configuration is invalid. Also the inspector button Generate. |
bool UpdateCenterFromPlayer() | Moves the streamed area to the player's current chunk. Does nothing while the player stays in the same chunk. Also the inspector button Recenter. |
ChunkCoord CenterFromPosition(Vector3 position) | The chunk coordinate of a world position. |
void Dispose() | Destroys the loaded chunks and the pool. Removes a player that the streamer spawned, but never a player you assigned. Also the button Clear World. |
void Rebuild() | Dispose() followed by Initialize(). Also the inspector button Rebuild. |
static int ChunkSizeMinimum(int maxRoomWidth, int maxRoomHeight, int safetyMarginCells) | Three times the largest room side, plus twice the safety margin. |
static int ChunkSizeRecommended(int maxRoomWidth, int maxRoomHeight, int safetyMarginCells) | The minimum plus MainPathWidthCells (2). |
State and events#
LoadedCount,PlannedCountint read-only- Number of chunks built and planned.
CenterChunkCoord,CenterKeystring read-only- The chunk the streamed area is centered on.
IsInitializedbool read-only- True after a successful
Initialize(). ChunkWorldTransform read-only- The root object of the streamed chunks.
LastErrorstring read-only- The most recent error message.
WorldChangedevent Action<Transform>- Raised with the world root.
Serialized fields#
The settings are described in Chunk Streaming settings. The most used ones are:
playerTransform,playerPrefabGameObject- The player that the streaming follows. A prefab is spawned at the entry room when no player is assigned.
corridorPrefabGameObject required- A 1 × 1 corridor module with one
DoorSocketon each cardinal side. There is no built-in fallback. useDedicatedEntrybool default on,entryPrefabsList<GameObject>- Dedicated entry rooms for the first room of each chunk. Off = pool-only mode.
roomPrefabsList<GameObject>- Rooms for the pool. Each one must have a
DoorSocketon every cardinal side. minRooms,maxRoomsint default 4 and 4- Rooms per chunk, Entry included.
cellsPerSideint default 24,cellSizefloat default 3- Chunk size in cells, and the size of one cell in meters. The cell size must match the room grid.
worldSeedint default 42,useRandomSeedbool default on- Repeatable world seed, and whether a new seed is drawn each time.
plannedRadiusint default 2,loadedRadiusint default 1- Planned and built radius in chunks.
loadedRadiusmust not exceedplannedRadius. lockChancefloat default 0,keyPrefabGameObject- Random lock fraction, and the key used to open locks.
materializePerFrameint default 1,materializeFrameBudgetMsfloat default 0- Build work per frame, and the optional millisecond budget. 0 turns the budget off.
prewarmRoomCopies,prewarmCorridorCopiesint default 4 and 24- Inactive copies created in advance for the rooms and corridor tiles.
Supporting chunk types#
These types back the streamer and are public in namespace DungeonGen. You rarely need them directly.
| Type | Role |
|---|---|
ChunkStreamer | Schedules loading and unloading. Dispose(), LoadedCount, and LastError. |
ChunkPlanner | Plans the layout of a chunk, deterministically, with Plan(settings, coord, worldSeed, …). Returns a ChunkPlanResult with a ChunkPlanStatus (Success, Failed) and a ChunkPlanFailureKind. |
ChunkMaterializer | Instantiates the rooms and corridor tiles of a plan. |
ChunkRoomProviderFactory | Measure(prefab, cellSize, out provider, out error) measures a room prefab. |
ChunkGridSettings | Chunk dimensions, room limits, and streaming distance. IsValid(out error) checks them. |
ChunkCoord | X, Z, Floor, Zero, and ToKey(). |
ChunkKeyPickup, ChunkRoomRequiresKey | Components for the key item, and for rooms that need a key. |
RoomDecorator and RoomDecorationAuthoring#
RoomDecorator is a plain C# class, not a component. It fills a room from a DecorationProfile. The editor preview and the runtime use the same solver. RoomDecorationAuthoring is the component on a room prefab. It holds a baked snapshot of the room geometry, and it creates a RoomDecorator at runtime when it is decorated.
Constructors: RoomDecorator(RoomDesign design, Transform root, DecorationProfile profile, int seed) and RoomDecorator(IRoomGeometry geo, Transform root, DecorationProfile profile, int seed).
| Member | Description |
|---|---|
DecorationResult DecorateAll() | Clears earlier placements, then solves every category, highest priority first. |
DecorationResult DecorateCategory(string categoryId) | Solves one category again. Removes its earlier instances first. |
void DespawnCategory(string categoryId), void DespawnAll() | Removes the instances of one category, or of all categories. |
IReadOnlyList<PlacedInstance> Placed | The current placements. |
RoomDecorationAuthoring#
ProfileDecorationProfile,Seedint default 12345- The profile and seed used for the room.
HasBakedDecorationbool- True when the furniture is saved in the prefab. The runtime then skips the room.
LastResultDecorationResult- The result of the last decoration run.
| Member | Description |
|---|---|
DecorationResult DecorateAll(int runtimeSeed) | Decorates the room with the given seed. Does nothing when the furniture is baked. |
DecorationResult DecorateCategory(string categoryId) | Decorates one category. |
DecorationResult RerollCategory(string categoryId) | Picks a new result for one category. Each call moves to the next result. |
void DespawnCategory(string categoryId), void DespawnAll() | Removes the decoration. |
void Initialize(DecorationProfile profile, int seed) | Sets the profile and the seed. |
void MarkDecorationBaked() | Marks the furniture as part of the prefab. |
Result types: DecorationResult (placed, diagnostics, hasErrors, errorMessage); PlacedInstance (instance, categoryId, categoryName, worldPosition, worldRotation, footprint, boundsSize, padding, floor, gridX, gridY, prefab, occupancy); GroupDiagnostic (targetCount, placedCount, candidateCount, solveMilliseconds, instantiateMilliseconds, groupDead, groupDeadReason, rejectionCounts).
Authoring enums: PlacementSurface, PlacementRegion, AmountMode, FailurePolicy, WallRegion, OccupancyMode, DistributionMode, OrientationMode, RelationType, FloorScope, and FitMode.
Rendering and room geometry#
IDungeonRenderer#
| Member | Signature |
|---|---|
| Render | void Render(DungeonData data, DungeonTheme theme, Transform root) |
| Clear | void Clear(Transform root) |
| PlaceCeilings | void PlaceCeilings(DungeonData data, DungeonTheme theme, Transform root) |
The default implementation is PrefabDungeonRenderer. Implement or wrap IDungeonRenderer to use another rendering backend.
IRoomGeometry#
The geometry contract for the decorator. It is implemented by RoomDesign in the editor and by RoomDecorationAuthoring at runtime. Members: Width, Height, FloorIndices, TileSize, FloorHeight, WallThickness, CenterPivot, GetFloor(int), InBounds(x, y), IsWallAt(x, y, floor), HasDoorAt, HasRoomDoorAt, IsStairFloorOpeningAt, IsStairCeilingOpeningAt, IsInStairFootprint, Doors, RoomDoors, and Stairs.
Post-processing and culling#
Post-processing contracts#
IDungeonPostProcessor:int Priority { get; }andvoid Process(DungeonPostProcessContext context). The manager runs every enabled processor on its GameObject after generation, highest priority first. Processors with equal priority keep their component order, andDungeonCullingruns last among them.DungeonPostProcessor: an abstractMonoBehaviourwith a serializedPriority. OverrideDefaultPriorityto change the value a new component starts with.DungeonPostProcessContext: a read-only snapshot of one run, withRunSeed,Root,Rooms,LayoutRooms, andConnections. It is valid only duringProcess.IDungeonPreClearProcessor:void BeforeClear(). It runs before the manager clears the rooms, so that a processor can release references to them, for example a baked NavMesh.
DungeonNavMeshPostProcessor#
Implements both contracts and bakes one NavMesh over the whole dungeon per generation. It requires DungeonNavMeshSurfaceHost, which is added automatically. The fields are described in the NavMesh guide. Key fields: agentTypeID, boundsPadding, layerMask, buildOnProcess, useDoorLinks, bakeConnectors, connectorWidth, logErrors.
DungeonCulling and rules#
DungeonCulling is an additive portal-culling post-processor. It reads the room graph and the door states, and changes only the rendering or activation of the rooms. Removing the component restores the normal behavior.
ModeDungeonCullingMode default DisabledDisabled(0),DisableRenderers(1), orDeactivateRooms(2).MaxHopsint default 4,OcclusionToleranceint default 0- Door distance from the reference room, and how many closed doors a room may lie behind.
ViewDistancefloat default 60,RevealDistancefloat default 45- Distance limit, and the smaller distance at which a hidden room becomes visible.
ProtectedNeighborHopsint default 1,MaxVisibleRoomsint default 0- Rooms kept visible next to the reference, and the visible room budget. 0 means no budget.
PollIntervalfloat default 0.25,MaxTogglesPerFrameint default 20- Seconds between checks, and the number of rooms switched per frame.
ReferenceTransformTransform,ReferencePositionVector3- The point the culling is measured from. Setting
ReferencePositionturns onUseReferencePosition. DebugDrawbool default off,CullLightsbool default on- Scene view gizmos, and whether the lights of hidden rooms are turned off.
UseDoorState,UseMaxHops,UseOcclusionTolerance,UseDistanceCulling,UseDistanceHysteresis,UseProtectedNeighborHops,UseVisibilityLeases,UseRoomRules,UseVisibleRoomBudgetbool default on- Switches for each mechanism.
| Member | Description |
|---|---|
void Refresh() | Applies the visibility to every room now. Use it after you change the state of the rooms by other means. |
void PollNow() | Checks the door states and the reference position now. |
bool IsRoomVisible(RoomData room) | The current visibility of a room. |
void SetReference(Transform reference) | Sets the reference transform. |
void SetConnectionRule(ICullConnectionRule rule) | Replaces the rule that decides whether a connection is passable. |
void AddRoomRule(ICullRoomRule rule), void RemoveRoomRule(ICullRoomRule rule) | Adds or removes a room rule. |
VisibilityLease AcquireVisibility(RoomData room, string reason = null, float durationSeconds = 0f) | Keeps a room visible until the returned lease is disposed, or until the duration ends. |
static void RegisterLocalViewpoint(Transform viewpoint), UnregisterLocalViewpoint | Registers a viewpoint that the culling uses when no reference is set. |
| Contract | Purpose |
|---|---|
ICullConnectionRule: bool IsPassable(DungeonConnectionInfo connection) | Decides whether a connection is passable for the visibility search. The default is DoorSocketRule, which passes a connection when both doors are open and unlocked. |
ICullRoomRule: bool? OverrideVisibility(RoomData room) | Forces a room visible or hidden. A null return leaves the decision to the rest of the culling. The first rule that returns a value wins. |
Authoring ScriptableObjects#
All assets are created with .
| Asset | Key members |
|---|---|
RoomDesign (Room Design) | roomName, roomType, width (default 12), height (default 10), activeFloor, doors, roomDoors, stairs, theme, decorationProfile, decorationSeed (default 12345), bakeDecorIntoPrefab; GetFloor(int), InBounds, IsWallAt, HasDoorAt, HasRoomDoorAt, IsStairFloorOpeningAt, IsStairCeilingOpeningAt, HasFloor, AddFloor, RemoveFloor, Floors, ToDungeonData(int). Structs: FloorTiles, StairPlacement, DoorPlacement, RoomDoorPlacement. |
DungeonTemplate (Dungeon Template) | nodes, edges, rootNodeId; FindNode(id), FindEdge(from, to), DefaultColor(RoomType). TemplateNode: id, type, pinnedPrefab, providedRequirements, graphPos. TemplateEdge: id, fromNode, toNode, requirement. |
DungeonTheme (DungeonTheme) | tileSize (default 1), floorHeight (default 3), wallThickness (default 0.25), doubleSidedWalls, doubleSidedCeilings, pivot (Corner or Center), prefabs (the TilePrefab entries with prefab, sizeX, sizeY, and canRotate), stairProfile, ResolveStairProfile(). |
DecorationProfile (Decoration Profile) | categories; FindCategory(id), GetSortedByPriority(). Each DecorationCategory has the surface, region, pool, footprint, relations, and failure policy. See the decoration guide. |
DoorSocketType (Door Socket Type) | DisplayName, Color, CompatibleTypes; SetCompatibleType(other, bool) writes both sides; HasCompatibleType(other); IsCompatibleWith(other). An untyped socket is a wildcard. |
ProgressionRequirement (Progression Requirement) | StableId, DisplayName, DefaultItemPrefab. Gates a main-path template edge. |
Progression contracts#
IItemSpawnPoint:bool CanSpawn(ProgressionRequirement requirement)andbool TrySpawn(ItemSpawnRequest request). The default isItemSpawnPoint, with an optional target transform and prefab override.ItemSpawnRequest: a readonly struct withrequirementandroomRoot.ProgressionItemToken: the component on a spawned item, withRequirementandConfigure(requirement).IConnectionGate:Requirement,IsLocked,CanHandle(requirement),Configure(requirement), andUnlock(). The default isBasicConnectionGate.
A gate on a door locks the connection until the requirement is unlocked, and an item spawn point in the providing room places the item. The guide Progression requirements describes the setup.
Supporting core types#
| Type | Role |
|---|---|
RoomData (MonoBehaviour) | Root component of a room prefab: width, height, tileSize, EffectiveTileSize, roomType, doorSockets, supportsDoubleWalls; TryGetOrderedSockets(out, out), FindSocket(gridX, gridY), CloseAllDoors(), OpenDoor(IDoorSocket), OpenDoorAt(gridX, gridY), Sockets. |
DoorSocket (MonoBehaviour) | The state of one doorway: IsOpen, IsLocked, Direction, SocketType, SocketRole (Unspecified, ExternalPortal, or InternalRoom). Setters: SetOpen(bool), SetPassage(), SetVariant(), SetLocked(bool), ShowConnectorVisual(int seed). |
RoomType and TileType | Room roles: Normal, Entrance, Exit, Treasure, Boss. Cell types: Empty, Floor, Wall, Door, CorridorFloor, CorridorWall, Hole, Ceiling. |
GeneratedRoomInfo (MonoBehaviour) | Marker on the root of each generated room. It holds the room's origin. |
DungeonObjectPool (MonoBehaviour) | Pooling of room and decoration prefabs at runtime. |
DungeonData, DungeonConfig | Data containers for the renderer and the generation pipeline. |
| Helpers | Corridor, Direction, Vec2Int, DoorConnectionResolver (socket matching), DungeonTemplateValidator, and DungeonTemplateGraph (main path and gate helpers). |
See also the Quick Start for the basic flow, and the Overview for the authoring and assembly model.