8

I have build a custom pyramid in Unity like this:

    Mesh mesh = GetComponent<MeshFilter>().mesh;
    mesh.Clear();
    Vector3[] vertices = {
        new Vector3(0.0f, 0.5f, 0.0f),
        new Vector3(0.5f, 0.0f, 0.5f),
        new Vector3(-0.5f, 0.0f, 0.5f),
        new Vector3(-0.5f, 0.0f, -0.5f),
        new Vector3(0.5f, 0.0f, -0.5f),
    };

    int[] triangles = {
        1, 2, 3,
        1, 3, 4,
        1, 0, 2,
        2, 0, 3,
        3, 0, 4,
        4, 0, 1
    };


    mesh.vertices = vertices;
    mesh.triangles = triangles;

I am trying to color my pyramid, as said in unity documentation like this:

    Color[] colors = new Color[vertices.Length];

    for (int i = 0; i < vertices.Length; i++)
        colors[i] = Color.Lerp(Color.red, Color.green, vertices[i].y);

    // assign the array of colors to the Mesh.
    mesh.colors = colors;

but this wont change a thing..

i have no materials on my object, only this script. Any ideas?

Iraklis Bekiaris
  • 1,163
  • 15
  • 43

2 Answers2

16

Note that comment in mesh.colors

// (Note that most built-in Shaders don't display vertex colors. Use one that does, such as a Particle Shader, to see vertex colors)

so in order to see those colors in the MeshRenderer component add a material that uses such a Vertex or Particle Shader.

Therefore

  1. in the Project view (Assets) do right click &rightarrow; Create &rightarrow; Material

    enter image description here

  2. Give that material a name

  3. For the Shader from the Dropdown menu find and select e.g. Particles &rightarrow; Standard Unlit (or if you want to receive lightning Standard Surface)

    enter image description here

  4. Finally use this material for your object either by dragging it into the MeshRenderer &rightarrow; material or by simply dragging it onto the according object in the Scene view (the latter might not work if there is no mesh for that object yet)


Result:

enter image description here

derHugo
  • 83,094
  • 9
  • 75
  • 115
3

In addition to https://stackoverflow.com/a/55714190/617889:

When using Universal Render Pipeline you need to use other shaders:

  • Univeral Render Pipeline \ Particles \ Lit (with lightning)
  • Univeral Render Pipeline \ Particles \ Unlit (without lightning)
oleh
  • 820
  • 2
  • 13
  • 28