Hi there, I’m making strategy game with tiles - every tile has unique index number that it gets recognized with and i have a matrix of those indexes that represends whole board. It looks like so (it’s smaller sample to make is easier to understand).
int[,] fieldIndexMatrix = new int[3, 3]; /* after initialization with indexes, example! \ y x \ 0 1 2 \___________________ | | | | 0 | 0 | 1 | 2 | |_____|_____|_____| | | | | 1 | 3 | 4 | 5 | |_____|_____|_____| | | | | 2 | 6 | 7 | 8 | |_____|_____|_____| */
So in the middle is field with index 4 and you get it by fieldIndexMatrix[1, 1], bottom left is field with index 6 and you get it by fieldIndexMatrix[2, 0], you get the idea
And let’s now say that i want some effect that will affect some targeted field and adjacent ones. Area of effect will be + looking so i need to find right, left, bottom, and upper field relative to targeted one.
I can find them by doing so:
List<int> adjacentIndexes = new List<int>(); int x;// x coordinate of the matrix int y;// y coordinate of the matrix int a; int b; a = x + 1; b = y; adjacentIndexes.Add(fieldIndexMatrix[a, b]); a = x - 1; b = y; adjacentIndexes.Add(fieldIndexMatrix[a, b]); a = x; b = y + 1; adjacentIndexes.Add(fieldIndexMatrix[a, b]); a = x; b = y - 1; adjacentIndexes.Add(fieldIndexMatrix[a, b]); return adjacentIndexes.ToArray();
While it will work for the fields in the middle It won’t for the fields on the edge. If my targeted field has coordinate x = 0 and I’ll try to find x - 1 I’ll get and error “IndexOutOfRangeException: Array index is out of range.” and my script will just stop there. but i don’t want it to stop!!!
I want it to keep going and finding indexes. If it can’t find an index because the coordinates for the matrix are out of range I just want to ignore this part and go to the next step. Is there some function or trick that can tell me If array index is in range of the matrix or not?
I tried doing
if(fieldIndexMatrix[a, b] != null) adjacentIndexes.Add(fieldIndexMatrix[a, b]);
but it does not seem to work. Any Idea?