2D Dungeon Generation with pathfinding

  • A* version: [enter version here]
  • Unity version: 2023.3.23f

Hey I am just writing this post to see if i could potentially get help on generating 2D graphs on runtime. I have managed to get the graphs created but Need help in aligning it to a tilemap and fitting the floor. The reason I need this is because the game is procedural and rooms are randomly spawned. If there is another solution I would love to hear it.

Code for reference.

using System.Linq;
using UnityEngine;
using UnityEngine.Tilemaps;
using Edgar.Unity;
using Pathfinding;


[CreateAssetMenu(menuName = "AI/Pathfinding", fileName = "GridGeneratorPostProcessing")]

public class PathfindingGenerator : DungeonGeneratorPostProcessingGrid2D
{
    public override void Run(DungeonGeneratorLevelGrid2D level)
    {
        foreach (var roomInstance in level.RoomInstances)
        {
            var roomTemplateInstance = roomInstance.RoomTemplateInstance;

            // Find floor tilemap layer
            var tilemaps = RoomTemplateUtilsGrid2D.GetTilemaps(roomTemplateInstance);
            Tilemap floor = tilemaps.Single(x => x.name == "Floor");

            // Use floor to create new graph for the pathfinding
            // This holds all graph data
            AstarData data = AstarPath.active.data;

            // This creates a Grid Graph
            GridGraph gg = data.AddGraph(typeof(GridGraph)) as GridGraph;
            gg.AlignToTilemap(floor.layoutGrid);
        }
    }
    }

Is the gg.AlignToTilemap(floor.layoutGrid) call not working as you wanted? From the code provided that looks correct to me, but let me know if it’s not working and I’ll look deeper into it :slight_smile:

when I look at the astar path component after it looks like the tilemap alignment doesn’t work at all. the dropdown menu stays empty on all the grids and the width and height remain at 10

Hey mate would love some help if you are still offering.

Absolutely :smiley: I’m usually unavailable over weekends, sorry about that.

Hmmm really? You have an object with the Tilemap and Tilemap Renderer in your scene too, right? Can you show me your settings for your graph and tilemap object?

The dropdown menu is used purely in the inspector. The AlignToTilemap method bypasses it. Don’t worry if the dropdown is empty.

The AlignToTilemap method will not change the width or height of the graph. It only aligns the graph to the closest orientation so that the grid nodes will be aligned to the cells in the tilemap.
You can adjust the width/height of the graph separately using e.g. graph.SetDimensions.

Thanks that makes more sense now.

I am also trying to figure out how to tick Use 2D physics within the code and how to move a graph.