Getting a error when i add coordinates of a blocked tile

hi there! im getting a error when i add coordinates of a blocked tile, in my case Red is my blockedColor, Green is my Walkable color/Default , gray is my path and white is explored, it works fine with coordinates where the path is Green but if i add coordinates that are colored in red, its giving this error:

KeyNotFoundException: The given key ‘(2, 3)’ was not present in the dictionary.
System.Collections.Generic.Dictionary`2[TKey,TValue].get_Item (TKey key) (at <5b93611b6ff043439d403fbb0837bc10>:0)

i can send more information if required :slight_smile:
PathFinder.ExploreNeighbors () (at Assets/PathFinding/PathFinder.cs:40)
PathFinder.Start () (at Assets/PathFinding/PathFinder.cs:23)

Hi verse,

We generate the keys for the dictionary in the CreateGrid method. There is a for-loop which generates coordinates starting from 0 to some value. Maybe that value is not high enough, so (2, 3) was not generated and added to the dictionary.

Please use Debug.Log to see what’s going on at runtime.


See also:

Hi, thank you for responding!, the Debug.Log in the CreateGrid method Does indeed work

heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridManager : MonoBehaviour
{
[SerializeField] Vector2Int gridSize;
Dictionary<Vector2Int, Node> grid = new Dictionary<Vector2Int, Node>();
public Dictionary<Vector2Int, Node> Grid { get { return grid; } }

void Awake()
{
    CreateGrid();
}

public Node GetNode(Vector2Int coordinates)
{
    if(grid.ContainsKey(coordinates))
    {
        return grid[coordinates];
    }

    return null;
}

void CreateGrid()
{
    for(int x = 0; x < gridSize.x; x++)
    {
        for(int y = 0; y < gridSize.y; y++)
        {
            Vector2Int coordinates = new Vector2Int(x,y);
            grid.Add(coordinates,  new Node(coordinates, true));
            Debug.Log(grid[coordinates].coordinates + "=" + grid[coordinates].isWalkable);
        }
    }
}

}

Fantastic. And did you see the (2, 3) key in the console? If not, the key is not included in the dictionary. If you saw it, check the order of the method calls. Maybe CreateGrid has not been executed yet when the other code tries to look for (2, 3) in the dictionary.

Oh, i see that (2,3) isn’t Printing to the console, how to exactly fix this?

i noticed in my PathFinder script i have a Debug.Log in the if(grid.ContainsKey(neighborCoords)) in ExploreNeighbors method but it isn’t Printing, Could that be related to the issue as well?

What are the values of gridSize.x and gridSize.y?

If (2, 3) is not included in the grid, grid.ContainsKey(neighborCoords) returns false if the neighborCoords are (2, 3). And if the condition was evaluated to false, the if-block does not get executed.

Privacy & Terms