Search Unity

Need help generating a number sequence.

Discussion in 'Scripting' started by RetnuhStudio, Apr 5, 2014.

  1. RetnuhStudio

    RetnuhStudio

    Joined:
    Jan 4, 2013
    Posts:
    28
    Hey guys,

    Been working on generating meshes in unity and am now trying to find a more automated and efficient way to generate the triangle int array.

    This is the sequence I need to generate.

    0, 1, 3,
    0, 3, 2,
    2, 3, 5,
    2, 5, 4,
    4, 5, 7,
    4, 7, 6......

    This is pretty much just working through the triangles in the below image, starting from the bottom and moving in a clockwise rotation through the vertices.

    $mesh_vertices.jpg

    At the moment I am hard coding all the values in like so.
    Code (csharp):
    1.  
    2. triangleArray = new int[] {
    3.  
    4.     0, 1, 3,
    5.     0, 3, 2,
    6.     2, 3, 5,
    7.     2, 5, 4,
    8.     4, 5, 7,
    9.     4, 7, 6,
    10.     6, 7, 9,
    11.     6, 9, 8,
    12.     8, 9, 11,
    13.     8, 11, 10,
    14.     10, 11, 13,
    15.     10, 13, 12,
    16.     12, 13, 15,
    17.     12, 15, 14,
    18.     14, 15, 17,
    19.     14, 17, 16,
    20.     16, 17, 19,
    21.     16, 19, 18,
    22.     18, 19, 21,
    23.     18, 21, 20 
    24. };
    25.  
    But this is not ideal due to the meshes being procedural with varying heights and vertex counts.
    So can anyone assist me on coding a function do generate that sequence dependent on the vertex count?.

    Regards
    - Matt
     
  2. Smooth-P

    Smooth-P

    Joined:
    Sep 15, 2012
    Posts:
    214
    I don't really know how building a mesh works, but this will call the specified action for each triangle in the sequence.

    Code (csharp):
    1.  
    2. public void Triangles(int height, Action<int, int, int> action) {
    3.     for (int i = 0; i < height; ++i) {
    4.         var a = 2 * i;
    5.         action(a, a + 1, a + 3);
    6.         action(a, a + 3, a + 2);
    7.     }
    8. }
    9.  
    Edit: Lols, I guess I should have actually read your post... How about:

    Code (csharp):
    1.  
    2. public int[] Triangles(int height) {
    3.     var triangles = new int[6 * height];
    4.  
    5.     for (int i = 0; i < height; ++i) {
    6.         var a = 2 * i;
    7.         var j = 6 * i;
    8.         triangles[j++] = a;
    9.         triangles[j++] = a + 1;
    10.         triangles[j++] = a + 3;
    11.         triangles[j++] = a;
    12.         triangles[j++] = a + 3;
    13.         triangles[j++] = a + 2;
    14.     }
    15.  
    16.     return triangles;
    17. }
    18.  
    19.  
    Edit: Fixed bug.
     
    Last edited: Apr 5, 2014
  3. RetnuhStudio

    RetnuhStudio

    Joined:
    Jan 4, 2013
    Posts:
    28
    Ha cheers Smooth P, Yea second function works nicely.