- Home /
Dijkstra Algorithm, ArgumentNullException: Argument cannot be null.
Hi I am trying to implement Dijkstras Algorithm as a basic pathfinding mathod on an chessboard like grid. I want place a block at every tile I used for a path between two tiles given by the user. I got it working so far, but when I try to use every tile just once, so it is blocked for every future path, I get this Error:
ArgumentNullException: Argument cannot be null.
Parameter name: key
System.Collections.Generic.Dictionary`2[UnityEngine.GameObject,System.Single].get_Item (UnityEngine.GameObject key) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:136)
DijkstraAlgorithm.Dijkstra (UnityEngine.GameObject[,] grid, UnityEngine.GameObject start, UnityEngine.GameObject end) (at Assets/Scripts/DijkstraAlgorithm.cs:50)
MouseScript.Update () (at Assets/Scripts/MouseScript.cs:41)
This would be my code:
static public Stack<GameObject> Dijkstra(GameObject[,]grid, GameObject start, GameObject end)
{
Dictionary<GameObject, float> dist = new Dictionary<GameObject, float>();
Dictionary<GameObject, GameObject> previous = new Dictionary<GameObject, GameObject>();
List<GameObject> Q = new List<GameObject>();
foreach(GameObject v in grid)
{
dist[v] = Mathf.Infinity;
previous[v] = null;
Q.Add(v);
}
dist[start] = 0;
while(Q.Count > 0)
{
float shortestDistance = Mathf.Infinity;
GameObject shortestDistanceNode = null;
foreach(GameObject obj in Q)
{
if (dist[obj] < shortestDistance )
{
shortestDistance = dist[obj];
shortestDistanceNode = obj;
}
}
GameObject u = shortestDistanceNode;
Q.Remove(u);
if(u==end)
{
Stack<GameObject> stack = new Stack<GameObject>();
while(previous[u] != null)
{
stack.Push(u);
u = previous[u];
}
return stack;
}
if(dist[u] == Mathf.Infinity)
{
break;
}
foreach(GameObject v in u.GetComponent<Node>().neighbors)
{
if(v.GetComponent<Node>().getBlocked()==false)
{
break;
}
float alt = dist[u] + (u.transform.position - v.transform.position).magnitude;
if(alt< dist[v])
{
dist[v] = alt;
previous[v] = u;
}
}
}
return null;
}
}
I hope someone here can help me, googleing the error has not produced anything helpfull. Thank you in advance Greets Harker
Looks like you're trying to use a null GameObject as a key in the dictionary. What line is that error on in your code?
The error appears when i add this line: if(v.GetComponent<Node>().getBlocked()==false)
Answer by CaKeMeaT · Aug 22, 2015 at 12:08 AM
if(v.GetComponent() != null && v.GetComponent().getBlocked()==false)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C#/Unity Stack size and memory leaks 5 Answers
Android blank screen when can't connect to server 0 Answers
How to ''stack'' coroutines, and call each one till all are executed? 5 Answers