Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question How to generate cylinders triangles with a loop

Discussion in 'Scripting' started by Deivydas4, Aug 11, 2023.

  1. Deivydas4

    Deivydas4

    Joined:
    Oct 28, 2021
    Posts:
    16
    Hello guys,
    I'm having a problem with generating a mesh. I have placed vertices in my scene and now I want to connect them to make triangles.

    Code (CSharp):
    1.         var triangleAngle = Mathf.PI * 2f / triangleCount;
    2.  
    3.         // Vertices
    4.         for (int z = 0; z <= cylinderheight; z++)
    5.         {
    6.             for (int i = 0; i < triangleCount; i++)
    7.             {
    8.                 var x = radius * Mathf.Cos(i * triangleAngle);
    9.                 var y = radius * Mathf.Sin(i * triangleAngle);
    10.                 vertices.Add(new Vector3(x, y, z));
    11.             }
    12.         }
    13.  
    14.         // Triangles
    15.         for (int z = 0; z <= cylinderheight; z++)
    16.         {
    17.             for (int i = 0; i < triangleCount; i++)
    18.             {
    19.                 int index0 = i;
    20.                 int index1 = i + 1;
    21.                 int index2 = i + 44;
    22.                 //int index3 = i + 45;
    23.  
    24.                 //if (i == triangleCount - 1)//special case
    25.                 //{
    26.                 //    index2 = 1; //second vertex of last triangle is vertex1
    27.                 //}
    28.  
    29.                 triangles.Add(index0);
    30.                 triangles.Add(index1);
    31.                 triangles.Add(index2);
    32.                 //triangles.Add(index3);
    33.             }
    34.         }
    Image:
    https://imgtr.ee/image/buOEG

    How to loop through for loop that it will nicely generate cylinder wall. By the way cylinder height is 44 and triangle count 45.

    Thank you for your help.
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,955
  3. Deivydas4

    Deivydas4

    Joined:
    Oct 28, 2021
    Posts:
    16
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    And here's mine, part of my MakeGeo project:

    https://github.com/kurtdekker/makegeo/blob/master/makegeo/Assets/makeuvcylinder/MakeUVCylinder.cs

    It writes UV coordinates as well but if you don't like the mapping, here's easy-cheesy triplanar remapper:

    https://github.com/kurtdekker/makegeo/blob/master/makegeo/Assets/setuvtoworld/SetUVToWorld.cs

    You can use the second script on any geometry from pretty much any source, as long as the mesh is read/write enabled.
     
    Deivydas4 likes this.