Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Failed setting triangles. Some indices are referencing out of bounds vertices.

Discussion in 'Scripting' started by Deleted User, Nov 26, 2014.

  1. Deleted User

    Deleted User

    Guest

    In the code below at line 25 I get this error:
    Failed setting triangles. Some indices are referencing out of bounds vertices.
    UnityEngine.Mesh:set_triangles(Int32[])

    Why do I get this error and how can I fix it?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class CreateMesh : MonoBehaviour {
    6.  
    7.     private Mesh mesh;
    8.  
    9.     void Start () {
    10.         GenerateMesh ();
    11.     }
    12.  
    13.     void GenerateMesh () {
    14.         mesh = new Mesh ();
    15.  
    16.         List<Vector3> vertices = new List<Vector3>();
    17.         List<int> triangles = new List<int>();
    18.         List<Vector2> uv = new List<Vector2>();
    19.  
    20.  
    21.         GeneratePlane (Vector3.zero, Vector3.up, Vector3.right, vertices, triangles, uv);
    22.         GeneratePlane (Vector3.forward, Vector3.up, -Vector3.forward, vertices, triangles, uv);
    23.  
    24.         mesh.vertices = vertices.ToArray();
    25.         mesh.triangles = triangles.ToArray();
    26.         mesh.uv = uv.ToArray();
    27.         mesh.RecalculateBounds();
    28.         mesh.RecalculateNormals();
    29.  
    30.         GetComponent<MeshFilter>().mesh = mesh;
    31.     }
    32.  
    33.     void GeneratePlane (Vector3 corner, Vector3 up, Vector3 right, List<Vector3> verts, List<int> tris, List<Vector2> uvs) {
    34.         verts.Add (corner);
    35.         verts.Add (corner + up);
    36.         verts.Add (corner + up + right);
    37.         verts.Add (corner + right);
    38.  
    39.         int index = tris.Count;
    40.         tris.Add(index + 0); tris.Add(index + 1); tris.Add(index + 2);
    41.         tris.Add(index + 2); tris.Add(index + 3); tris.Add(index + 0);
    42.  
    43.         uvs.Add(new Vector2(0, 0));
    44.         uvs.Add(new Vector2(0, 1));
    45.         uvs.Add(new Vector2(1, 1));
    46.         uvs.Add(new Vector2(1, 0));
    47.     }
    48. }
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The indices in the triangles need to refer to the appropriate vertices; using tris.Count will not work. Using verts.Count would, I think, but you'd have to do that first.

    --Eric
     
    Deleted User likes this.
  3. Deleted User

    Deleted User

    Guest

    Thank you!
    It works!