- Home /

# Can I check if pair of indexes are in range of the matrix?

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?

**Answer** by akillingbeck
·
Sep 06, 2017 at 11:58 AM

fieldIndexMatrix .GetLength() function, passing in the dimension you want to test will give you the size.

Using that with a < 0 check before you use fieldIndexMatrix[a, b] will avoid out of range exceptions

### Your answer

### Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.