开发者

ArgumentOutOfRangeException Was Unhandled

开发者 https://www.devze.com 2023-04-05 20:37 出处:网络
Further details of the exception: Index was o开发者_如何转开发ut of range. Must be non-negative and less than the size of the collection. Parameter name: index

Further details of the exception: Index was o开发者_如何转开发ut 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.


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.


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.


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;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号