Search Unity

Feedback Problems with Advanced Mesh API to generate mesh from code

Discussion in 'General Graphics' started by KarlosEnd, Sep 28, 2022.

  1. KarlosEnd

    KarlosEnd

    Joined:
    Oct 6, 2019
    Posts:
    1
    Hello, could someone help me with this? I'm trying to use the advanced mesh api to generate my chunks but I don't know what I'm doing wrong. the first image shows how it was done before, and the second, with the advanced mesh api.




    I also can't find a way to add vertex colors.

    Code (CSharp):
    1.  
    2.     public byte[,,] voxels = new byte[VoxelData.ChunkWidth, VoxelData.ChunkHeight,      VoxelData.ChunkWidth];
    3.  
    4.     public int vertexIndex = 0;
    5.     public List<Vector3> vertices = new List<Vector3>();
    6.     public List<int> triangles = new List<int>();
    7.     public List<Vector2> uvs = new List<Vector2>();
    8.     public List<Color32> colores = new List<Color32>();
    9.  
    10.  public Mesh CreateMesh2(){
    11.         // Asignar datos de malla para una malla.
    12.         var dataArray = Mesh.AllocateWritableMeshData(1);
    13.         var data = dataArray[0];
    14.         // Vértices con posiciones y normales.
    15.         data.SetVertexBufferParams(vertices.Count,
    16.             new VertexAttributeDescriptor(VertexAttribute.Position),
    17.             new VertexAttributeDescriptor(VertexAttribute.Normal, stream: 1)
    18.             //,
    19.             //new VertexAttributeDescriptor(VertexAttribute.Color,VertexAttributeFormat.Float32)
    20.             );
    21.    
    22.         // El primer flujo de datos del búfer de vértices son solo posiciones;
    23.         // llenarlos.
    24.         var pos = data.GetVertexData<Vector3>();
    25.  
    26.         for (int i = 0; i < pos.Length; i++)
    27.         {
    28.             pos[i] = vertices[i];
    29.         }
    30.         // Nota: las normales se calcularán más adelante en RecalculateNormals.
    31.  
    32.         data.SetIndexBufferParams(vertexIndex, IndexFormat.UInt16);
    33.         var ib = data.GetIndexData<ushort>();
    34.         for (ushort i = 0; i < ib.Length; ++i)
    35.             ib[i] = (ushort)triangles[i];
    36.  
    37.         // Una submalla con todos los índices.
    38.         data.subMeshCount = 1;
    39.         data.SetSubMesh(0, new SubMeshDescriptor(0, ib.Length));
    40.         // Crear la malla y aplicarle datos:
    41.         var mesh = new Mesh();
    42.         mesh.name = "chunk";
    43.         Mesh.ApplyAndDisposeWritableMeshData(dataArray, mesh);
    44.         mesh.colors32 = colores.ToArray();
    45.         mesh.RecalculateNormals();
    46.         mesh.RecalculateBounds();
    47.  
    48.         return mesh;
    49.     }

    Thanks for reading all these! D: