Home > OS >  Index out of bounds error when rendering mesh in Unity
Index out of bounds error when rendering mesh in Unity

Time:03-15

I'm trying to render a hexagon in unity using these coordinates
https://qph.fs.quoracdn.net/main-qimg-9ad01ef3babb64b57d378a1558f468a7

What I'm getting, is this error:

Failed setting triangles. Some indices are referencing out of bounds vertices. IndexCount: 18, VertexCount: 7

Any ideas what is wrong with this code?

    void Start()
    {
        MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>();

        Mesh mesh = new Mesh();

        Vector3[] vertices = new Vector3[7]
        {
            new Vector3(0, 0),
            new Vector3(-1.0f, 0),
            new Vector3(-0.5f, Mathf.Sqrt(3/2)),
            new Vector3(0.5f, Mathf.Sqrt(3/2)),
            new Vector3(1, 0),
            new Vector3(0.5f, - Mathf.Sqrt(3/2)),
            new Vector3(-0.5f, - Mathf.Sqrt(3/2))
        };
        mesh.vertices = vertices;

        int[] tris = new int[18]
        {
            
            0, 2, 1,
            0, 3, 2,
            0, 4, 3,
            0, 5, 4,
            0, 6, 5,
            0, 7, 6
        };
        mesh.triangles = tris;

        meshFilter.mesh = mesh;
    }

CodePudding user response:

The last triangle uses the vertex at index 7 which does not exist since you specified the hexagon to have only 7 points. In case you don't know, indexes start at 0 which is why this doesn't work (although by the looks of it you already know this, though you could be blindley following a tutorial which is why I said this).

It should be 1 instead of 7, since you have to loop back around and connect a triangle between index 6 (the last index) and the first perimeter index, which is index 1.

  • Related