vedaloivdocs

Reference

Dungeon API Reference

Documentation for v1.1.0namespace DungeonGenUnity 6000.5.0+

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
  1. Namespace overview
  2. DungeonManager
  3. Methods
  4. Status and events
  5. Serialized fields
  6. ChunkDungeonStreamer
  7. Methods
  8. State and events
  9. Serialized fields
  10. Supporting chunk types
  11. RoomDecorator and RoomDecorationAuthoring
  12. RoomDecorationAuthoring
  13. Rendering and room geometry
  14. IDungeonRenderer
  15. IRoomGeometry
  16. Post-processing and culling
  17. Post-processing contracts
  18. DungeonNavMeshPostProcessor
  19. DungeonCulling and rules
  20. Authoring ScriptableObjects
  21. Progression contracts
  22. Supporting core types

Namespace overview#

AreaTypes
GenerationDungeonManager, ChunkDungeonStreamer, ChunkStreamer, ChunkPlanner, ChunkMaterializer, ChunkRoomProviderFactory, RoomDecorator, RoomDecorationAuthoring
RenderingIDungeonRenderer, PrefabDungeonRenderer, DungeonTheme
Post-processing and cullingIDungeonPostProcessor, IDungeonPreClearProcessor, DungeonPostProcessor, DungeonPostProcessContext, DungeonNavMeshPostProcessor, DungeonNavMeshSurfaceHost, DungeonCulling, ICullConnectionRule, ICullRoomRule, DoorSocketRule
Authoring assetsRoomDesign, DungeonTemplate, DecorationProfile, DoorSocketType, ProgressionRequirement
Geometry and coreIRoomGeometry, RoomData, DoorSocket, GeneratedRoomInfo, DungeonObjectPool, DungeonData, DungeonConfig
ProgressionIItemSpawnPoint, ItemSpawnPoint, ItemSpawnRequest, IConnectionGate, BasicConnectionGate, ProgressionItemToken
EnumsDungeonGenerationMode, 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#

MemberDescription
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#

Status DungeonGenerationStatus read-only
State of the latest run: Idle, Generating, Ready, Failed, or Cancelled. A failed run keeps the previous dungeon.
IsGenerating bool read-only
True while Status is Generating.
GenerationProgress float read-only, 0 to 1
Progress of the current run.
StatusChanged event 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.

template DungeonTemplate required
Generation stops with an error when it is empty.
generationMode DungeonGenerationMode default TemplateExact
TemplateExact (0) or TemplateSequencedRandom (1).
useBurstPlanner, addRandomBranchesInExact bool default off
Burst planner, and random branches in exact mode.
roomPool List<RoomPoolEntry>
Weighted candidates: prefab, weight (minimum 0; the constructor default is 1), and allowedContexts. An empty context value means all contexts.
maxSearchNodes int default 10000, minimum 100
Placement attempts before the planner gives up.
allowRotation bool default on
Allows 90° steps to match socket directions.
mainPathRoomCount, minOffshootSequenceFillers, maxOffshootSequenceFillers, maxRandomBranchRooms, minRandomBranchStarts, maxRandomBranchStarts, allowRandomSubbranches, maxRandomBranchDepth int, bool
Sequenced random tuning. Defaults: 10, 0, 2, 10, 1, 1, on, 4.
seed int default 0, useRandomSeed bool default on
The seed is used when useRandomSeed is off.
seamPadding, allowedSeamOverlap float default 0 and 0
Space kept between adjacent rooms, and the overlap allowed at a seam.
wallMode SeamMode default SingleOnly
SingleOnly (0), DoubleOnly (1), or AllowBoth (2). See Wall mode.
root Transform null = this transform
Parent for the instantiated rooms.
sceneEntrance RoomData
Optional room placed in the scene, used as the root of the dungeon.
useEntranceSeamPadding, entranceSeamPadding bool, float default off and 0
Seam padding for the rooms attached directly to sceneEntrance.
prototypePlayerPrefab, spawnPrototypePlayer GameObject, bool empty and on
Player spawned at the entrance in Play Mode after generation.
generationFrames int default 1, generationFrameBudgetMs float 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, decorationPoolPrewarm int default 5 and 20
Pre-created copies of each room and decoration prefab.
prewarmOnAwake bool default on
Runs PrewarmForGeneration in Awake.
maxPlanRetries int default 50, planRetryTimeoutMs int default 2000
Retries with a new seed when rooms do not fit, and the time limit for all retries.
decorateAfterGeneration bool default on
Decorates each room that has a RoomDecorationAuthoring.
logGeneration, logDecorationDiagnostics bool 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#

MemberDescription
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, PlannedCount int read-only
Number of chunks built and planned.
Center ChunkCoord, CenterKey string read-only
The chunk the streamed area is centered on.
IsInitialized bool read-only
True after a successful Initialize().
ChunkWorld Transform read-only
The root object of the streamed chunks.
LastError string read-only
The most recent error message.
WorldChanged event Action<Transform>
Raised with the world root.

Serialized fields#

The settings are described in Chunk Streaming settings. The most used ones are:

player Transform, playerPrefab GameObject
The player that the streaming follows. A prefab is spawned at the entry room when no player is assigned.
corridorPrefab GameObject required
A 1 × 1 corridor module with one DoorSocket on each cardinal side. There is no built-in fallback.
useDedicatedEntry bool default on, entryPrefabs List<GameObject>
Dedicated entry rooms for the first room of each chunk. Off = pool-only mode.
roomPrefabs List<GameObject>
Rooms for the pool. Each one must have a DoorSocket on every cardinal side.
minRooms, maxRooms int default 4 and 4
Rooms per chunk, Entry included.
cellsPerSide int default 24, cellSize float default 3
Chunk size in cells, and the size of one cell in meters. The cell size must match the room grid.
worldSeed int default 42, useRandomSeed bool default on
Repeatable world seed, and whether a new seed is drawn each time.
plannedRadius int default 2, loadedRadius int default 1
Planned and built radius in chunks. loadedRadius must not exceed plannedRadius.
lockChance float default 0, keyPrefab GameObject
Random lock fraction, and the key used to open locks.
materializePerFrame int default 1, materializeFrameBudgetMs float default 0
Build work per frame, and the optional millisecond budget. 0 turns the budget off.
prewarmRoomCopies, prewarmCorridorCopies int 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.

TypeRole
ChunkStreamerSchedules loading and unloading. Dispose(), LoadedCount, and LastError.
ChunkPlannerPlans the layout of a chunk, deterministically, with Plan(settings, coord, worldSeed, …). Returns a ChunkPlanResult with a ChunkPlanStatus (Success, Failed) and a ChunkPlanFailureKind.
ChunkMaterializerInstantiates the rooms and corridor tiles of a plan.
ChunkRoomProviderFactoryMeasure(prefab, cellSize, out provider, out error) measures a room prefab.
ChunkGridSettingsChunk dimensions, room limits, and streaming distance. IsValid(out error) checks them.
ChunkCoordX, Z, Floor, Zero, and ToKey().
ChunkKeyPickup, ChunkRoomRequiresKeyComponents 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).

MemberDescription
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> PlacedThe current placements.

RoomDecorationAuthoring#

Profile DecorationProfile, Seed int default 12345
The profile and seed used for the room.
HasBakedDecoration bool
True when the furniture is saved in the prefab. The runtime then skips the room.
LastResult DecorationResult
The result of the last decoration run.
MemberDescription
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#

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 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; } and void 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, and DungeonCulling runs last among them.
  • DungeonPostProcessor: an abstract MonoBehaviour with a serialized Priority. Override DefaultPriority to change the value a new component starts with.
  • DungeonPostProcessContext: a read-only snapshot of one run, with RunSeed, Root, Rooms, LayoutRooms, and Connections. It is valid only during Process.
  • 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.

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.

Mode DungeonCullingMode default Disabled
Disabled (0), DisableRenderers (1), or DeactivateRooms (2).
MaxHops int default 4, OcclusionTolerance int default 0
Door distance from the reference room, and how many closed doors a room may lie behind.
ViewDistance float default 60, RevealDistance float default 45
Distance limit, and the smaller distance at which a hidden room becomes visible.
ProtectedNeighborHops int default 1, MaxVisibleRooms int default 0
Rooms kept visible next to the reference, and the visible room budget. 0 means no budget.
PollInterval float default 0.25, MaxTogglesPerFrame int default 20
Seconds between checks, and the number of rooms switched per frame.
ReferenceTransform Transform, ReferencePosition Vector3
The point the culling is measured from. Setting ReferencePosition turns on UseReferencePosition.
DebugDraw bool default off, CullLights bool default on
Scene view gizmos, and whether the lights of hidden rooms are turned off.
UseDoorState, UseMaxHops, UseOcclusionTolerance, UseDistanceCulling, UseDistanceHysteresis, UseProtectedNeighborHops, UseVisibilityLeases, UseRoomRules, UseVisibleRoomBudget bool default on
Switches for each mechanism.
MemberDescription
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), UnregisterLocalViewpointRegisters a viewpoint that the culling uses when no reference is set.
ContractPurpose
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 Assets › Create › DungeonGen › ….

AssetKey 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) and bool TrySpawn(ItemSpawnRequest request). The default is ItemSpawnPoint, with an optional target transform and prefab override.
  • ItemSpawnRequest: a readonly struct with requirement and roomRoot.
  • ProgressionItemToken: the component on a spawned item, with Requirement and Configure(requirement).
  • IConnectionGate: Requirement, IsLocked, CanHandle(requirement), Configure(requirement), and Unlock(). The default is BasicConnectionGate.

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#

TypeRole
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 TileTypeRoom 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, DungeonConfigData containers for the renderer and the generation pipeline.
HelpersCorridor, 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.