- Home /
List gives "Array index is out of range" for no reason
Hi!
How can this possibly give the forementioned error?
RaycastHit2D[] hit;
hit = Physics2D.RaycastAll (position, transform.right);
for(int i = 0; i < hit.Length; i++){
if(hit[i+1] != null){
Debug.Log(hit[i+1].collider.name);
secondTarget = hit[i+1].transform;
break;
}
}
The code compiles, but it give a runtime error and doesnt function correctly.
Answer by fafase · Jun 02, 2014 at 06:15 PM
First off, nothing happens for no reason in a computer, particularly with such a beginner error.
if(hit.Length > i){
Debug.Log(hit[i+1].collider.name);
secondTarget = hit[i+1].transform;
break;
}
So you have an array and you want to perform the action if the i is smaller than hit.Length.
Consider your length to be 10, you list is from 0 to 9. So on the run when i is 9, it is smaller than 10 but you use i + 1 in the method trying to access the index 10 that is out of bound.
See, there is always a reason, even if a bug, the bug has a reason. Computers are dumb.
Yea i noticed that myself, i edited the code, to what i meant it to be. What is weird, is that the hit[i+1] is not null but it still gives this error (index is out of range)
Sorry for the wrong code at first.
Just read through it again, it might be likely that perfor$$anonymous$$g that action when i is smaller than hit length is the problem.
Also, did you get any script errors when saving? Are you not able to use play mode?
Answer by rutter · Jun 02, 2014 at 09:08 PM
Classic "off by one" error.
Your loop runs from 0
to Length
.
Inside the loop, you access i+1
. On the last iteration, i+1
is out of bounds.
You can fix this by checking if i
is equal to Length-1
before accessing the array, or by changing your loop so that it runs from 0
to Length-1
.
Usually Length used in cycles without "-1", you just shouldn't check if counter <= Length. $$anonymous$$aybe I'm wrong, but i consider "Length-1" as bad tone in this case. We can just put i < length.
Your answer
Follow this Question
Related Questions
How do I find a local variables index in a foreach loop? 1 Answer
Array index is out of range and Raycast question 0 Answers
For all elements above a certain index 1 Answer
How do I return the index of an array of sprites as an int? 1 Answer
Find specific element when duplicates exist in list. 1 Answer