0
\$\begingroup\$

I'm trying to draw a gizmo sphere at the location of each vertex in my mesh with the following code:

private void OnDrawGizmos()
    {
        MeshFilter selectedMeshFilter = (MeshFilter)objecttodraw.GetComponent("MeshFilter");
        Mesh mesh = selectedMeshFilter.sharedMesh;
        Vector3[] vertices = mesh.vertices;
        Color[] colors = new Color[vertices.Length];
        for (var i = 0; i <= vertices.Length; i++)
        {
            Gizmos.DrawSphere(vertices[i], vertices.Length);
        }
    }

I'm getting an exception, "Array index is out of range" on this line:

Gizmos.DrawSphere(vertices[i], vertices.Length);

IndexOutOfRangeException: Array index is out of range.

GetBounds.OnDrawGizmos () (at Assets/Scripts/GetBounds.cs:32)

UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Arrays in C# are zero-based. That means an array of vertices of length 4 has entries at:

0, 1, 2, 3

Trying to access an entry at index 4 is asking for the fifth item from a list of four things — so the runtime complains that you're indexing out of the array's bounds.

Your for loop should look like this:

for( int i = 0, i < vertices.Length; i++)

With a "less than" in the test, not "less than or equal to"

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .