Categories
Mastering Development

Index Out Of Range Exception C# Unity

I am trying to create a grid of vertices, where every other row is offset and also has one additional vertex in that row. I have succeeded in getting the vertices in the right shape, but it is giving me an “IndexOutOfRangeException: Index was outside the bounds of the array.”

Here is my code:

public class HexGrid : MonoBehaviour {

private Vector3[] vertices; 


public int width = 6;
public int height = 6;
public float outterRadius = HexMetrics.outerRadius; // controls the spacing

void Awake ()
{
    generate();
}

void generate ()
{

    vertices = new Vector3[width*height + height/2]; 

    for (int i = 0, y = 0; y < height+1; y++)
    {
        for (int x = 0; x < width + y%2; x++, i++)
        {
            Vector3 position;
            position.x = (x - (y * 0.5f) + (y / 2)) * (HexMetrics.innerRadius * 2f);  
            position.y = 0f;
            position.z = y * (HexMetrics.outerRadius * 1.5f);

            vertices[i] = new Vector3(position.x, 0, position.z);             
        }        
    }
}

private void OnDrawGizmos()
{
    if (vertices == null)
    {
        return;
    }

    Gizmos.color = Color.black;
    for (int i = 0; i < vertices.Length; i++)
    {
        Gizmos.DrawSphere(vertices[i], 0.1f);
    }
}

}

Thanks in advance.

Leave a Reply

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