I've been playing around with using recursion for the path finding

here’s what I used for the PathFind() Method in PathFinder. Not sure if it’s better to do this or not, just thought it would be a fun thought experiment as a new programmer

private void PathFind() {
        searchCenter = queue.Dequeue();
        searchCenter.Explored = true;
        if (searchCenter.Equals(endWayPoint)) {
            return;
        } else {
            ExploreNeighbors();
            PathFind();
        }
    }

Here’s the rest of the class if you like

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PathFinder_Recursive : MonoBehaviour {

    Dictionary<Vector2Int, Waypoint> grid = new Dictionary<Vector2Int, Waypoint>();

    [SerializeField] Waypoint startWayPoint = null;
    [SerializeField] Waypoint endWayPoint = null;
    Queue<Waypoint> queue = new Queue<Waypoint>();
    Waypoint searchCenter;
    
    Vector2Int[] directions = {
        Vector2Int.up,
        Vector2Int.right,
        Vector2Int.down,
        Vector2Int.left
    };

    void Start() {
        Initialize();                            
        LoadBlocks();
        ColorStartAndEnd();
        PathFind();
    }

    private void Initialize() {
        queue.Enqueue(startWayPoint);
    }

    private void PathFind() {
        searchCenter = queue.Dequeue();
        searchCenter.Explored = true;
        if (searchCenter.Equals(endWayPoint)) {
            return;
        } else {
            ExploreNeighbors();
            PathFind();
        }
    }

    private void LoadBlocks() {
        var waypoints = FindObjectsOfType<Waypoint>();
        foreach (Waypoint waypoint in waypoints) {
            var gridPos = waypoint.GetGridPos();
            if (grid.ContainsKey(gridPos)) {
                Debug.LogWarning("Skipping overlapping block" + waypoint);
            } else {
                grid.Add(gridPos, waypoint);
            }
        }
    }

    private void ColorStartAndEnd() {
        startWayPoint.SetTopColor(Color.green);
        endWayPoint.SetTopColor(Color.red);
    }

    private void ExploreNeighbors() {
        foreach (Vector2Int direction in directions) {
            Vector2Int neighborCoordinates = searchCenter.GetGridPos() + direction;
            try {
                QueueNewNeighbors(neighborCoordinates);
            } catch {
            }
        }
    }

    private void QueueNewNeighbors(Vector2Int neighborCoordinates) {
        Waypoint neighbor = grid[neighborCoordinates];
        if (!neighbor.Explored && neighbor.ExploredFrom == null) {
            queue.Enqueue(neighbor);
            neighbor.ExploredFrom = searchCenter;
        }
    }
}

Privacy & Terms