- Home /
Array index is out of range - A* Open list.
I've been trying to figure out what's wrong with this code for a long time now with no success, no matter what I've tried. I don't know why, but apparently the open node isn't in the grid when I know for a fact that it is.
I'll post the code on the Pastebin link below as it is fairly long.
Look for line 148. Can someone please look over it and make sure there are no daft errors which I've not seen?
Thanks.
I'd start by putting a debug statement on the line before and output the values of those x and z values.
Ok given we know that the grid is complete (because you are drawing it, right?) $$anonymous$$y first thought would be that there's something screwy going on with the .Contains() using Vector3s as perhaps they aren't co$$anonymous$$g out equal. For my implementation of a grid I used a class containing three ints to represent positions so that comparisons are more likely to succeed.
Also are you getting exceptions in all those empty catch blocks in your GetAdjacentNodes function? Exceptions are performance costly...
I guess a try catch around 148 with a debug log showing the values of .z and .x would help narrow it down...
I followed a tutorial for the a* algorithm and in the tutorial I was told to do the try catch, I'm fairly new to pathfinding however I understand the algorithm clearly. I'll try what you suggested and post the result...
Answer by Unitraxx · Apr 10, 2013 at 04:21 PM
I think the problem originates from building your grid.
line 215:
gridWidth = Mathf.RoundToInt(bounds.size.x / gridSize);
gridLength = Mathf.RoundToInt(bounds.size.z / gridSize);
grid = new Node[gridWidth, gridLength];
Do you take in account the behaviour of RountToInt? (Because you don't use it anywhere else) and that the maximum index is one smaller than the size you give up? I'm thinking that you are just giving larger values than your max index.
It has to be an integer as you can't use a decimal with an index.
Yeah sure, but at other points you always use a cast to int, ins$$anonymous$$d of RountToInt.
FloorToInt might be a better choice though - it has consistent behaviour
Answer by luckruns0ut · Apr 10, 2013 at 04:36 PM
I think I have found the problem, or at least one error: I was passing the x and z axes through the grid[,] and didn't think to realize that they can't be negative. Also, how can I modify the algorithm to check if a path is even possible because the game will just crash if there is no path available.
When your open list is empty and you aren't at the destination then there is no path.