How to fix Index Out Of Range errors in Unity3D

A very common problem in Unity programming is the Index Out Of Bounds Exception

A related cousin is the Argument Out Of Range Exception.

Both mean the same thing. One is for arrays, one is for other types of collections.

What it means is you have a collection of items, but you’re asking for something outside of that collection.

For instance if you have three things, you are asking for the fourth (or greater) one.

Keep in mind that if you have three things, they will be indexed by 0, 1, 2.

If you ask for thing at index 3, that is the fourth thing and it is out of range of a three-thing collection.

Similarly, if you ask for thing -1 (minus one), that also cannot happen.

Another tricky part of this one is that often when you doubleclick on the error, Unity does not take you to the offending line of code, or else it takes you to the wrong line of code.

However, you can still get there manually by looking at the error text itself.

Select the error in the console window and then look down in the lower panel of the console window. Find the first line that is your script, and that will contain a number that tells you where the error is. In some newer versions of Unity you can even click in that window to be taken there.

If after all that you are baffled by why you are getting this error, and you are POSITIVE that there are enough items in your collection to satisfy your dereference operation, then you need to put a Debug.Log() call right before the point where you get the error, and print out two things: the index you are dereferencing, and the Count (or Length) of the collection itself.

Now you have some information to go track down why in fact you do not have enough items in the array.

0 Shares

Leave a Reply

Your email address will not be published. Required fields are marked *