- Home /
How to check if a c# 3d array index exists?
How do I check if a multi-dimentional array index reference is beyond the range of the array?
GameObject[, ,] objectMatrix = null;
void Start () {
objectMatrix = new GameObject[9,33,33]; //range is less than 100
}
void Update () {
if(objectMatrix[100,100,100] == ???){ //Code stops here. This index does not exist.
print("This index is beyond the array's range.");
}
print (objectMatrix[100,100,100]); //Code stops anytime the index is out of range.
}
The above paraphrased code fails to do anything. It just stops at the illegal index in either the print function or if statement; no errors or warnings. What can I replace the '???' with to check if the index is legal?
I'm using this array to store the 3d grid locations of cubes, to check that no cube is generated at an occupied address, and eventually to save/load the arrangement.
Answer by robertbu · Aug 31, 2013 at 12:48 AM
You can use GetLength() with the index of the dimension to check an index against the size before accessing:
GameObject[, ,] objectMatrix = null;
void Start () {
objectMatrix = new GameObject[11,22,33]; //range is less than 100
Debug.Log(objectMatrix.GetLength(0)+","+objectMatrix.GetLength(1)+","+objectMatrix.GetLength(2));
}
The Debug.Log() output, "11,22,33."
Your answer
Follow this Question
Related Questions
Array index out of range after build 1 Answer
Array Index out of range (JavaScript) 1 Answer
Arrays rebels to my power! 1 Answer
Array Index Out of Range 2 Answers