Toonyoshi123
Toonyoshi123

Reputation: 31

How do I change the colors of triangles inside a procedurally generated mesh during generating?

I'm using unity, c#, and I cannot figure out how I can generate a landscape with all different kinds of height colors. For instance, I want sand near the water and snow on mountain peaks. But I cannot manage to make this happen in code where the mesh is being generated.

Just to make clear, The mesh generates perfectly fine, but I cannot manage to change the colors of each separate triangle.

 void CreateMesh()
{
    planeMesh = new Mesh();
    List<Vector3> vertices = new List<Vector3>();
    List<Vector2> uvs = new List<Vector2>();
    List<int> indices = new List<int>();
    List<Color> colors = new List<Color>();

    for (int x = 0; x < gridSize + 1; x++)
    {
        for (int y = 0; y < gridSize + 1; y++)
        {
            float height = Mathf.PerlinNoise(y / (float)gridSize, x / (float)gridSize) * 15.0f;
            vertices.Add(new Vector3(y, height, x));
            if(height > 12)//mountain tops
            {
                uvs.Add(new Vector2(0, 1/3));//down to up, x first
                colors.Add(Color.white);
            }
            else if(height > 3 && height < 13)//grassy fields
            {
                uvs.Add(new Vector2(1/3,2/3));
                colors.Add(Color.green);
            }
            else if(height > 0 && height < 4)//sand
            {
                uvs.Add(new Vector2(2/3, 2/3));
                colors.Add(Color.yellow);
            }
        }
    }

    //making the indices
    for (int b = 0; b < gridSize; b++)
    {
        for (int c = 0; c < gridSize; c++)
        {
            indices.Add(b + ((gridSize + 1) * c));
            indices.Add(b + gridSize + 1 + ((gridSize + 1) * c));
            indices.Add(b + 1 + ((gridSize + 1) * c));

            indices.Add(b + gridSize + 1 + ((gridSize + 1) * c));
            indices.Add(b + gridSize + 2 + ((gridSize + 1) * c));
            indices.Add(b + 1 + ((gridSize + 1) * c));
        }
    }

    planeMesh.SetVertices(vertices);
    planeMesh.SetIndices(indices.ToArray(), MeshTopology.Triangles, 0);
    planeMesh.SetUVs(0, uvs);

    planeMesh.RecalculateNormals();
    planeMesh.colors = colors.ToArray();

    GetComponent<MeshFilter>().mesh = planeMesh;
    GetComponent<MeshFilter>().mesh.name = "Environment";

}

Could you guys help me with that?

Upvotes: 1

Views: 693

Answers (1)

Toonyoshi123
Toonyoshi123

Reputation: 31

Solved it! It seems the numbers I was using for the uvs were being rounded down to 0! I had to make them floats to use them properly.

Upvotes: 2

Related Questions