Solution of KeyNotFoundException (and a question)

I tried to set coordinates (0,0) in the inspector(Path Finder Script) result was:
image

and if I set to coordinates (2, 0)
image

Probably more experienced people could solve this very quickly. But It was hard to find for me. I couldn’t even know how to trigger this exception.

  • I tried to compare my script to Garry’s script. Everything was same
  • I tried to compared other scripts.
  • Then I replaced my tiles again (because I had mistake before but haven’t fixed it yet).
  • I tried to factory reset to my pc, cleaned to house, changed to my phone number but none of these worked.

Then, I changed to value of Grid Size in inspector with bigger number like (50, 50) (It was 2,1 before) problem solved. Gary didn’t trigger this exception. I guess that’s because he set Grid Size values to (4 , 2) in Dictionaries lesson (at 09:40) and checked (0,0) and (2,1) coordinates in PathFinder.

GridSize = (0, 0) & PathFinder Coordinates = (2, 0) → No Exception
GridSize = (2, 1) & PathFinder Coordinates = (2, 0) → Exception
GridSize = (2, 2) & PathFinder Coordinates = (2, 0) → Exception

What’s going on in here actually?

Hi Yavuz,

Have you already tried to take a look into the dictionary during runtime? If the (2, 0) block exists, (2, 0) should be a key in the dictionary and it should be added at some point.

1 Like

The problem here is something commonly called an “off by one error” and is always a bit of a pain!

To explain, let’s look at the base case of having a grid size of 1x1. This would only contain the node with coordinates of (0,0). Notice here that both the x- and y- coordinates are one less than the corresponding coordinates for the grid size.

By extension, a grid size of 2x1 would contain the nodes; (0,0) and (1,0).
So, when you try to find a path to the node at coordinate (2,0), it’s not present in the dictionary and you get the KeyNotFound exception.

To fix this, remember that the grid size must always be at least one higher than the coordinates of the node you’re trying to reach.
Therefore, you could fix this with a grid size at least 3x1, since this would contain the nodes at; (0,0), (1,0), and (2,0).

I hope that helps explain this problem you’re experiencing and gives you an idea of how to avoid it in the future.

1 Like

Everything is clear! I appreciate for your answers :slight_smile: @garypettie, @Nina .
To explain my question better for future questions, here is what I mean:

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms