Reputation: 81
Further details of the exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
When reading the exception, I understand what it's trying to tell me. What I don't understand is -why- it's coming up. Here is the snippet of relevant code:
//the model contains more than one mesh, so each
//one must be accounted for in the final sphere
List<BoundingSphere> spheres = new List<BoundingSphere>();
int index = 0;
//cycle through the meshes
foreach (ModelMesh mesh in this.model.Meshes)
{
//and grab its bounding sphere
spheres[index++] = mesh.BoundingSphere; //<- this is the line that throws the exception
} //end foreach
While debugging, I can see in the table provided by Visual Studio that my model.Meshes.Count is 5, and that at the current iteration, index is 1. Index is less than the size of my collection, and it is non-negative.
What's throwing the exception? I've tried searching for similar examples, but haven't found anything to quite answer my question yet.
Thanks in advance.
Upvotes: 0
Views: 2303
Reputation: 43066
You need to use the Add method to increase the size of the list. So try spheres.Add(mesh.BoundingSphere);
rather than spheres[index++] = mesh.BoundingSphere;
Upvotes: 1
Reputation: 19070
You meant to write spheres.Add(mesh.BoundingSphere)
. Your spheres
list is empty after you created it. You cannot access an item which is not there.
Upvotes: 1
Reputation: 100620
You need to use list.Add(...) instead of indexing.
List's size is 0 by deafult and you can add items, but you code indexing non-existent item. It will fail even on index = 0.
Upvotes: 3