Iraklis Bekiaris
Iraklis Bekiaris

Reputation: 1221

Unity | mesh.colors won't color my custom mesh object

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?

Upvotes: 8

Views: 9600

Answers (2)

oleh
oleh

Reputation: 960

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)

Upvotes: 3

derHugo
derHugo

Reputation: 90724

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 clickCreateMaterial

    enter image description here

  2. Give that material a name

  3. For the Shader from the Dropdown menu find and select e.g. ParticlesStandard 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 MeshRenderermaterial 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

Upvotes: 17

Related Questions