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.

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.

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.