C# Index is Out Of Range (But it is not)
int p = System.Array.IndexOf (AlivePlatforms,Plat.gameObject);
for (int n = p; n < AlivePlatforms.Length; n++) {
if (AlivePlatforms [n + 1]) {
if (n + 1 < AlivePlatforms.Length -1) {
AlivePlatforms [n] = AlivePlatforms [n + 1];
}
}
else{
AlivePlatforms[n] = null;
break;
}
print ("N: " + n);
}
I have an array called ActivePlatforms. It has a length of 20, so 0-19 should be acceptable indices. I define a variable called p to be the index of a certain game object. In my test runs p has always below 2 or 3. The for loop is supposed to run through a loop starting at p and basically remove p while moving each other value above it down by 1. There is only about 8 objects in the 20 size AlivePlatforms array.
So basically what I am trying to do is remove an element form the middle of an array and move all the elements above (at a greater index) it down one. Yet it says index is out of range. The print statement was put in to tell me at what index it is out of range. It never prints past 5 before it tells me, but the Arrays length is 20. I even put in an if statement to make sure n is always less then Aliveplatforms length. I can't figure out how the index is out of range when it has no possible way to be greater or equal to the length, and in my test runs never became greater than 5.
Thank you for your help.
Your print statement is at the bottom of the loop, so it won't run if there was an error. Also your code makes assumptions about what p might be, which is never a good idea. If the condition is "n < AlivePlatforms.Length" and you immediately try to access "AlivePlatforms [n + 1]", that's bound to fail.
As an aside, any reason you're not using a List and Remove/RemoveAt rather than trying to do this manually?
Answer by Bunny83 · Oct 24, 2016 at 02:18 AM
Well, this line:
if (AlivePlatforms [n + 1]) {
Will fail for "n == 19".
I guess your condition should simply be
if (n+1 < AlivePlatforms.Length)
{
AlivePlatforms [n] = AlivePlatforms [n + 1];
}
else
{
AlivePlatforms[n] = null;
break;
}
You could also use
if (n+1 < AlivePlatforms.Length && AlivePlatforms[n + 1] != null)
To only iterate up to the first null value.
Thank you for your answer. The problem ended up being that n would sometimes equal -1. I guess this is the default value returned if Array.IndexOf() does not include the object you are searching for. Though I am pretty sure my object is in the array, I just added a check to make sure n did not equal -1 and it seems to work fine. Thanks again!
Answer by NotEnoughLemons3D · Oct 24, 2016 at 02:16 AM
Figured out the issue. Array.IndexOf() was returning -1.
Of course that's an additional problem if the object isn't inside the array.
Your answer
![](https://koobas.hobune.stream/wayback/20220612095310im_/https://answers.unity.com/themes/thub/images/avi.jpg)