Did the challenge a bit differently

So glad that I was able to write out the challenge with no issues.
I also did it a bit differently from the course material, but it works :fireworks:

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

public class Pathfinder : MonoBehaviour
{
    [SerializeField] private Node currentSearchNode;
    private Vector2Int[] directions = {Vector2Int.right,
                                       Vector2Int.left,
                                       Vector2Int.up,
                                       Vector2Int.down};
    private GridManager gridManager;

    private void Awake() {
        gridManager = FindObjectOfType<GridManager>();
    }

    private void Start() {
        ExploreNeighbors();
    }

    private void ExploreNeighbors() {
        List<Node> neighbors = new List<Node>();

        foreach (Vector2Int direction in directions) {
            Vector2Int neighborCoordinates =
                              currentSearchNode.coordinates + direction;
            if (gridManager == null) { return; }
            Node neighbor = gridManager.GetNode(neighborCoordinates);
            if (neighbor == null) { return; }
            neighbors.Add(neighbor);

            // TODO remove after testing
            Dictionary<Vector2Int, Node> grid = gridManager.Grid;
            grid[neighborCoordinates].isExplored = true;
            grid[currentSearchNode.coordinates].isPath = true;
        }
    }
}

Unless Iโ€™m missing something Iโ€™m not sure this works. As soon as a neighbor is null you stop processing neighbors. So, if the currentSearchNode is anywhere along the right edge of the grid, you will not have any neighbors processed. Left edge will not have any neighbors above or below it. Etc.
You probably wanted

if (neighbor == null) continue;

because this would end the current iteration and move to the next direction.
You also donโ€™t need to check if (gridManager == null) on every iteration. You can do this outside the foreach

You are right. Later down the line it made problems and was changed.

1 Like

Itโ€™s a good solution, just had a few minor issues.

1 Like

Privacy & Terms