- Home /
How can I loop over all vertices and draw triangles ? I'm getting out of range exception
private int counter = 0;
public Vector3[] newVertices;
private void Start()
{
Mesh meshprefab = meshPrefab.GetComponent<MeshFilter>().sharedMesh;
newVertices = meshprefab.vertices;
for (int i = 0; i < newVertices.Length; i++)
{
try
{
DrawLine(newVertices[counter], newVertices[counter + 1], Color.red);
DrawLine(newVertices[counter + 1], newVertices[counter + 2], Color.red);
DrawLine(newVertices[counter + 2], newVertices[counter], Color.red);
}
catch(Exception err)
{
string tt = "";
}
counter = counter + 3;
}
}
For example in this case in the array newVertices there are 350 items. Now I want to create triangles so my formula is to move counter forward each time by 3. Then in the first loop counter is 0. So I'm connecting the points 0 to 1 then 1 to 2 then 2 to 0 and that's a triangle.
The problem is when 'i' in the loop is getting to 116.
i = 116 counter = 348 newVertices = 350
So now when it's doing counter + 2 it's 350 so it's out of range.
The question is how and what should I do to solve it ? I want to connect and draw all vertices triangles but it's drawing only 116.
Something I miss here and I guess I don't understand yet.
I understand why it's giving the exception but not how to solve it and draw all the triangles.
Answer by poisoned_banana · Apr 21, 2018 at 09:44 AM
just use 'i', the variable in your loop
for(int i=0; i<newVertices.length-2;i++){
DrawLine(newVertices[i], newVertices[i + 1], Color.red);
DrawLine(newVertices[i + 1], newVertices[i+ 2], Color.red);
DrawLine(newVertices[i+ 2], newVertices[i], Color.red);
}
Your answer
Follow this Question
Related Questions
How can i prevent from mouse to collide with thirdpersoncontroller ? 0 Answers
How can i pick two randomly items from gameobject array ? 1 Answer
Script for a hue rainbow scroll on the material 1 Answer
How can i using a break point if a gameobject have a collider after added to it ? 1 Answer
How can i get all childs from List ? 3 Answers